What I want.
In a tab sliding menu context, I want to replace a fragment to another inside a tab, and maintaining the tab menu, and also the current tab
Based on what you explained I Implement following:
1- In your Activity create your Tabs
and ViewPager
:
mPager = (ViewPager) findViewById(R.id.vp_pager);
mPager.setOffscreenPageLimit(3);
PagerAdapter mAdapter = new PagerAdapter(getSupportFragmentManager(), getContext());
mPager.setAdapter(mAdapter);
//tab.setupWithViewPager(mPager);
2- In each Tabs create ViewPager
(I assume you want tabs inside tabs
if you don't need tabs just removed them), Implementation of each fragment
would be something like :
ViewPager mPager = (ViewPager) rootView.findViewById(R.id.vp_pager);
mPager.setOffscreenPageLimit(3);
CategoryAdapter mAdapter = new CategoryAdapter(getChildFragmentManager());//make sure this ChildFragmentManager
mPager.setAdapter(mAdapter);
Also in fragment create a Button which when Click goes to another fragment:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPager.setCurrentItem(1); // go to second fragment
}
});
final result would be something like following and when If you go to Home Tabs and then goes back to Category Tab you're your Fragment
position not changed.
Two point you should remember:
mPager.setOffscreenPageLimit(3);
if you don't want to destroy your fragmentgetChildFragmentManager()
instead of FragmentManager()
If you don't need Inner ViewPager
And you Just want load one instance of Fragment at time here is another option:
1- Do first item of previous way.
2- In your fragment xml put FrameContainer and load your fragment inside it:
CategoryResultFragment f = CategoryResultFragment.newInstance();
getFragmentManager().beginTransaction()
.replace(R.id.frame_result_container, f)
.commit();
Edit: This is not best approach but I think solve your issue:
1- Create a static field in your MainActivity
like following:
static String[] type = new String[3];
2- When you call onClick in your fragment, update String
value in your MainActivity
.
public static update currentType(int pos,String type);
first value is ViewPager position, Second value is your inner Fragment type (e.g: fragment_d);
3- In your ViewPager
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: // first tab
if(type[position] == "fragment_d")
return new Fragment_D();
else
return new Fragment_B();
}
}