Friday, March 25, 2016

Change or Replace Fragments Inside ViewPager

MainActivity.java

package android.zafar.viewpager;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;

/**
 * Example about replacing fragments inside a ViewPager. I'm using
 * android-support-v7 to maximize the compatibility.
 *
 * @author Zafar Imam
 *
 */
public class MainActivity extends ActionBarActivity {

// For this example, only two pages
static final int NUM_ITEMS = 2;

ViewPager mPager;
SlidePagerAdapter mPagerAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

/* Instantiate a ViewPager and a PagerAdapter. */
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new SlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);

}

/* PagerAdapter class */
public class SlidePagerAdapter extends FragmentPagerAdapter {
public SlidePagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int position) {
/*
* IMPORTANT: This is the point. We create a RootFragment acting as
* a container for other fragments
*/
if (position == 0)
return new RootFragment();
else
return new StaticFragment();
}

@Override
public int getCount() {
return NUM_ITEMS;
}
}


}

Then Create Three different Fragments As :

FirstFragemt.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class FirstFragment extends Fragment {

private static final String TAG = "FirstFragment";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.first_fragment, container, false);

Button btn = (Button) view.findViewById(R.id.btn);

btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
FragmentTransaction trans = getFragmentManager()
.beginTransaction();
/*
* IMPORTANT: We use the "root frame" defined in
* "root_fragment.xml" as the reference to replace fragment
*/
trans.replace(R.id.root_frame, new SecondFragment());

/*
* IMPORTANT: The following lines allow us to add the fragment
* to the stack and return to it later, by pressing back
*/
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(null);

trans.commit();
}
});

return view;
}


}

SecondFragment .java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;


public class SecondFragment extends Fragment {

private static final String TAG = "SecondFragment";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater
.inflate(R.layout.second_fragment, container, false);

Button btn = (Button) view.findViewById(R.id.btn);

btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
FragmentTransaction trans = getFragmentManager()
.beginTransaction();
trans.replace(R.id.root_frame, new StaticFragment());
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(null);
trans.commit();
}
});

return view;
}


}


StaticFragment.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class StaticFragment extends Fragment {

private static final String TAG = "StaticFragment";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater
.inflate(R.layout.static_fragment, container, false);

return view;
}

}

Then create a root fragment which contains Framelayout as

RootFragment.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class RootFragment extends Fragment {

private static final String TAG = "RootFragment";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* Inflate the layout for this fragment */
View view = inflater.inflate(R.layout.root_fragment, container, false);

FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
/*
* When this container fragment is created, we fill it with our first
* "real" fragment
*/
transaction.replace(R.id.root_frame, new FirstFragment());

transaction.commit();

return view;
}

}


Now create the respected layout files for each one as : 

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>


first_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="#d6b90512"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:padding="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge" 
        android:textColor="#fff"
        android:text="Fragmet One" />
    <Button 
        android:id="@+id/btn"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:text="@string/to_second_fragment"/>

</RelativeLayout>



second_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#d6b90512">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:padding="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#fff"
        android:text="Fragment Second" />
    <Button 
        android:id="@+id/btn"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:text="@string/to_static_fragment"/>

</RelativeLayout>



static_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="#d6b90512"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:padding="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#fff"
        android:text="Static Fragment" />

</RelativeLayout>


root_fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="#000"
    android:layout_height="match_parent"
    android:id="@+id/root_frame" >

</FrameLayout>

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="android.zafar.viewpager"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat.Light.DarkActionBar" >
        <activity
            android:name="com.pineappslab.frcontainer.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>



Output Screen Shots :







No comments:

Post a Comment