Well you have multiple ways of achieving your "i want to view new fragment".
By "new fragment" you could mean "new content and ui" if that's so, you could "cheat" your way out and inflate a layout with overlaying views, that you set to VISIBLE
or GONE
.
E.g.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:id="@+id/lyt_stuff_a"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/txt_stuff_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This stuff is for content a" />
</LinearLayout>
<LinearLayout
android:id="@+id/lyt_stuff_b"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/txt_stuff_b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This stuff is for content b"
android:visibility="gone" />
</LinearLayout>
</RelativeLayout>
So in code you just switch your content by
getView().findViewById(R.id.lyt_stuff_a).setVisibility(View.GONE);
getView().findViewById(R.id.lyt_stuff_b).setVisibility(View.VISIBLE);
But this approach might bloat your View tree, if your layout is very complex. And also the appropriate Fragment might do too much stuff, that you would like to separate in multiple Fragments.
If that's the case, you have to be aware of configuration changes or restarts of your App and handle those changes (i.e. save your state and reinitialize the right Fragments). If you are ok with that, you can change Fragments inside a ViewPager during runtime:
public class TabsPagerAdapter extends FragmentPagerAdapter {
protected Fragment[] fragments;
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
initFragPageCount();
}
private void initFragPageCount() {
fragments = new Fragment[3];
}
@Override
public int getCount() {
return fragments.length;
}
@Override
public Fragment getItem(int position) {
Fragment f = fragments[position];
if (f == null) {
f = initFragment(position);
}
return f;
}
private Fragment initFragment(int position) {
Fragment f = fragments[position];
if (f == null) {
switch (position) {
case 0:
f = new HomePage();
fragments[position] = f;
break;
case 1:
f = new GetContacts();
fragments[position] = f;
break;
case 2:
f = new Settings();
fragments[position] = f;
break;
}
}
return f;
}
public void replaceFrag(Fragment f, int index) {
if (index > 0 && index < fragments.length) {
fragments[i] = f;
}
notifyDataSetChanged();
}
}
You can replace it like this (e.g. in your Button's OnClickListener
):
adaptPager.replaceFrag(new FragReplacement(), 2); // replaces the third Fragment in the Pager