What I want to do is, pass a sorting variable into specific ViewPager's fragment
My ViewPager is work. I used OnPageChangeListener to get the current fragment and current tab position.
But, when I pass the variable outside the Listener, it always changed to 0
code: currentPos = arg0; (arg0 is returning correct position)
System.out.println("Current:" + currentPos);
All Tab Display result: Current:0
ThirdTab.java:
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
public Fragment fragment;
public int currentPos;
public String getSorting() {
return sorting;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.third_tab, container, false);
setHasOptionsMenu(true);
tabs = (PagerSlidingTabStrip) rootView.findViewById(R.id.slidingTabStrip);
pager = (ViewPager) rootView.findViewById(R.id.pager);
adapter = new MyPagerAdapter(getChildFragmentManager(), getActivity().getApplicationContext());
adapter.setTitle(catType);
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
System.out.println("Good" + arg0);
fragment = ((MyPagerAdapter) pager.getAdapter()).getFragment(arg0);
currentPos = arg0;
if (arg0 == 1 && fragment != null) {
fragment.onResume();
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.menuSortRecentCreate:
case R.id.menuSortRecentUpdate:
case R.id.menuSortLowestPrice:
case R.id.menuSortHighestPrice:
if (item.getItemId() == R.id.menuSortRecentCreate) {
sorting = "0";
} else if (item.getItemId() == R.id.menuSortRecentUpdate) {
sorting = "1";
} else if (item.getItemId() == R.id.menuSortLowestPrice) {
sorting = "2";
} else if (item.getItemId() == R.id.menuSortHighestPrice) {
sorting = "3";
}
System.out.println("Current:" + currentPos);
System.out.println("Current Page:" + pager.getCurrentItem());
return true;
case R.id.action_search:
return true;
case R.id.action_setting:
ThirdTabTaskSettingActivity fragment = new ThirdTabTaskSettingActivity();
mainActivity.pushFragments(getResources().getString(R.string.title_third_tab), fragment, true, true);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
MyPagerAdapter in ThirdTab.java
public class MyPagerAdapter extends FragmentStatePagerAdapter {
private String[] TITLES = {};
private String[] PERSONAL_TITLES = { getString(R.string.personal_category1), getString(R.string.personal_category2), getString(R.string.personal_category3),
getString(R.string.personal_category4), getString(R.string.personal_category5), getString(R.string.personal_category6) };
private String[] BUSINESS_TITLES = { getString(R.string.business_category1), getString(R.string.business_category2), getString(R.string.business_category3),
getString(R.string.business_category4), getString(R.string.business_category5) };
HashMap<Integer, Fragment> hm = new HashMap<Integer, Fragment>();
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private Context mContext;
public MyPagerAdapter(FragmentManager fm, Context context) {
super(fm);
mFragmentManager = fm;
mFragmentTags = new HashMap<Integer, String>();
mContext = context;
}
public void setTitle(String category) {
if (category.equals("personal")) {
TITLES = PERSONAL_TITLES;
}
else {
TITLES = BUSINESS_TITLES;
}
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = ThirdTabContentFragment1.newInstance(position, sorting, keyword);
return fragment;
case 1:
fragment = ThirdTabContentFragment2.newInstance(position, sorting, keyword);
return fragment;
case 2:
fragment = ThirdTabContentFragment3.newInstance(position, sorting, keyword);
return fragment;
case 3:
fragment = ThirdTabContentFragment4.newInstance(position, sorting, keyword);
return fragment;
case 4:
fragment = ThirdTabContentFragment5.newInstance(position, sorting, keyword);
return fragment;
case 5:
fragment = ThirdTabContentFragment6.newInstance(position, sorting, keyword);
return fragment;
}
return fragment;
// return SuperAwesomeCardFragment.newInstance(position, sorting, keyword);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
System.out.println("instantiate");
Object obj = super.instantiateItem(container, position);
if (obj instanceof Fragment) {
Fragment f = (Fragment) obj;
String tag = f.getTag();
mFragmentTags.put(position, tag);
}
return obj;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
public Fragment getFragment(int position) {
System.out.println("In:" + position);
String tag = mFragmentTags.get(position);
if (tag == null) { return null; }
return mFragmentManager.findFragmentByTag(tag);
}
}
ReceiveData's Fragment
public class ThirdTabContentFragment1 extends BaseContainerFragment implements AsyncResponse {
public static ThirdTabContentFragment1 newInstance(int position, String vSorting, String vKeyword) {
ThirdTabContentFragment1 f = new ThirdTabContentFragment1();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
System.out.println("a" + position);
return f;
}
#Override
public void onResume() {
System.out.println("Resume1");
super.onResume();
}
}
Related
I have an activity which consists of three fragments. In one of these fragments I have a viewpager that consists of three other fragments. I call getChildFragmentManager() inside fragment that has viewpager in it. I have searched SO and read almost every answer that are related to this topic for example: this and this and one that seemed most useful was this but could not solve my problem. I think if i can just return POSITION_NONE for getItemPosition(Object object) in FragmentStatePagerAdapter and call notifyDataSetChanged() will solve my problem but every time I do this my app crashes with this error:
java.lang.IllegalStateException: FragmentManager is already executing
transactions!!!
and I mentioned that I am using getChildFragmentManager() inside my fragment.
Anyone thinks of any solution to this problem?
this is the parent fragment:
public class WordDetailFragment extends Fragment {
#BindView(R.id.word_parts_tab_layout)
TabLayout mTabLayout;
#BindView(R.id.word_part_view_pager)
ViewPager mViewPager;
private WordPagerAdapter mPagerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_word_detail, container, false);
ButterKnife.bind(this, view);
mPagerAdapter = new WordPagerAdapter(getChildFragmentManager(), getActivity());
mViewPager.setAdapter(mPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
return view;
}
public void notifyTranslateChanged() {
mViewPager.getAdapter().notifyDataSetChanged();
}
}
this is the code for adapter
public class WordPagerAdapter extends FragmentStatePagerAdapter {
final int PAGE_COUNT = 3;
private String[] tabTitles = new String[]{"Definition", "Example", "Col & fam"};
private Context context;
public WordPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch (position) {
case 0:
fragment = new WordDefinitionFragment();
break;
case 1:
fragment = new WordExampleFragment();
break;
case 2:
fragment = new WordColFamFragment();
break;
default: fragment = new WordDefinitionFragment();
}
return fragment;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
One of the fragments in viewpager
public class WordDefinitionFragment extends Fragment {
#BindView(R.id.show_translate_switch)
Switch mShowTranslateSwitch;
private List<WordInfo> mWordInfoList;
private List<Definition> mDefinitionList;
private boolean mShowTranslation;
private View mView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_word_definition, container, false);
ButterKnife.bind(this, mView);
mShowTranslation = SharedPrefHelper.getBooleanInfo(getActivity(), getString(R.string.show_translate_key));
mShowTranslateSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (getActivity() != null)
((WordActivity) getActivity()).changeTranslateMode(b);
showTranslation(b);
}
});
return mView;
}
}
and my activity. U have just included the parts that i felt are needed here.
public class WordActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceSate) {
super.onCreate(savedInstanceSate);
setContentView(R.layout.activity_word);
}
public void changeTranslateMode(boolean show) {
SharedPrefHelper.setBooleanInfo(this, getString(R.string.show_translate_ke)y, show);
((WordDetailFragment)mWordDetailFragment).notifyTranslateChanged();
}
}
and my logcat error is
After many searches I could figure out a way which is not very smart but for the time being has solved my problem.
First of all I used the class FixedFragmentStatePagerAdapter from this post. I also had to remove the part in which the fragment bundle is restored because it caches fragment variables and views.
public abstract class FixedFragmentStatePagerAdapter extends PagerAdapter {
private static final String TAG = "PagerAdapter";
private static final boolean DEBUG = false;
private final FragmentManager mFragmentManager;
private FragmentTransaction mCurTransaction = null;
private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<>();
private ArrayList<String> mSavedFragmentTags = new ArrayList<>();
private ArrayList<Fragment> mFragments = new ArrayList<>();
private Fragment mCurrentPrimaryItem = null;
public FixedFragmentStatePagerAdapter(FragmentManager fm) {
mFragmentManager = fm;
}
/**
* Return the Fragment associated with a specified position.
*/
public abstract Fragment getItem(int position);
public String getTag(int position) {
return null;
}
#Override
public void startUpdate(ViewGroup container) {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// If we already have this item instantiated, there is nothing
// to do. This can happen when we are restoring the entire pager
// from its saved state, where the fragment manager has already
// taken care of restoring the fragments we previously had instantiated.
if (mFragments.size() > position) {
Fragment f = mFragments.get(position);
if (f != null) {
return f;
}
}
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
Fragment fragment = getItem(position);
String fragmentTag = getTag(position);
if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment + " t=" + fragmentTag);
/* if (mSavedState.size() > position) {
String savedTag = mSavedFragmentTags.get(position);
if (TextUtils.equals(fragmentTag, savedTag)) {
Fragment.SavedState fss = mSavedState.get(position);
if (fss != null) {
fragment.setInitialSavedState(fss);
}
}
}*/
while (mFragments.size() <= position) {
mFragments.add(null);
}
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
mFragments.set(position, fragment);
mCurTransaction.add(container.getId(), fragment, fragmentTag);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment)object;
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object
+ " v=" + ((Fragment)object).getView() + " t=" + fragment.getTag());
while (mSavedState.size() <= position) {
mSavedState.add(null);
mSavedFragmentTags.add(null);
}
mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment));
mSavedFragmentTags.set(position, fragment.getTag());
mFragments.set(position, null);
mCurTransaction.remove(fragment);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment)object;
if (fragment != mCurrentPrimaryItem) {
if (mCurrentPrimaryItem != null) {
mCurrentPrimaryItem.setMenuVisibility(false);
mCurrentPrimaryItem.setUserVisibleHint(false);
}
if (fragment != null) {
fragment.setMenuVisibility(true);
fragment.setUserVisibleHint(true);
}
mCurrentPrimaryItem = fragment;
}
}
#Override
public void finishUpdate(ViewGroup container) {
if (mCurTransaction != null) {
mCurTransaction.commitAllowingStateLoss();
mCurTransaction = null;
mFragmentManager.executePendingTransactions();
}
}
#Override
public boolean isViewFromObject(View view, Object object) {
return ((Fragment)object).getView() == view;
}
#Override
public Parcelable saveState() {
Bundle state = null;
if (mSavedState.size() > 0) {
state = new Bundle();
Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
mSavedState.toArray(fss);
state.putParcelableArray("states", fss);
state.putStringArrayList("tags", mSavedFragmentTags);
}
for (int i=0; i<mFragments.size(); i++) {
Fragment f = mFragments.get(i);
if (f != null) {
if (state == null) {
state = new Bundle();
}
String key = "f" + i;
mFragmentManager.putFragment(state, key, f);
}
}
return state;
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
if (state != null) {
Bundle bundle = (Bundle)state;
bundle.setClassLoader(loader);
Parcelable[] fss = bundle.getParcelableArray("states");
mSavedState.clear();
mFragments.clear();
ArrayList<String> tags = bundle.getStringArrayList("tags");
if (tags != null) {
mSavedFragmentTags = tags;
} else {
mSavedFragmentTags.clear();
}
if (fss != null) {
for (int i=0; i<fss.length; i++) {
mSavedState.add((Fragment.SavedState)fss[i]);
}
}
Iterable<String> keys = bundle.keySet();
for (String key: keys) {
if (key.startsWith("f")) {
int index = Integer.parseInt(key.substring(1));
Fragment f = mFragmentManager.getFragment(bundle, key);
if (f != null) {
while (mFragments.size() <= index) {
mFragments.add(null);
}
f.setMenuVisibility(false);
mFragments.set(index, f);
} else {
Log.w(TAG, "Bad fragment at key " + key);
}
}
}
}
}
}
Then I implemented ViewPager.OnPageChangeListener in the fragment that contains the viewpager. And in the void onPageScrollStateChanged(int state) method I updated the view of my fragments in viewpager.
public class WordDetailFragment extends Fragment implements ViewPager.OnPageChangeListener {
#BindView(R.id.word_parts_tab_layout)
TabLayout mTabLayout;
#BindView(R.id.word_part_view_pager)
ViewPager mViewPager;
private WordPagerAdapter mPagerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_word_detail, container, false);
ButterKnife.bind(this, view);
mPagerAdapter = new WordPagerAdapter(getChildFragmentManager(), getActivity());
mViewPager.setAdapter(mPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mViewPager.addOnPageChangeListener(this);
return view;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
Fragment mFragment;
#Override
public void onPageSelected(int position) {
mFragment = mPagerAdapter.getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (mFragment instanceof WordDefinitionFragment) {
((WordDefinitionFragment) mFragment).showTranslation();
//Log.e("StateChanged", mFragment.getClass().getSimpleName());
}
if (mFragment instanceof WordExampleFragment) {
((WordExampleFragment) mFragment).showTranslation();
//Log.e("StateChanged", mFragment.getClass().getSimpleName());
}
if (mFragment instanceof WordColFamFragment) {
((WordColFamFragment) mFragment).showTranslation();
//Log.e("StateChanged", mFragment.getClass().getSimpleName());
}
}
}
}
And in my fragments, I had a callback interface which was implemented in the activity. And in void setUserVisibleHint(boolean isVisibleToUser) method I updated the UI again because neighbor fragments did not get updated.
public class WordExampleFragment extends Fragment {
#BindView(R.id.example_field_name_id)
TextView mExampleFieldNameTV;
#BindView(R.id.word_tv)
TextView mWordTv;
#BindView(R.id.play_sound_iv)
ImageView mPlaySoundIv;
#BindView(R.id.show_translate_switch)
Switch mShowTranslateSwitch;
private TextView mExample1ContentFaTV;
private List<WordInfo> mWordInfoList;
private List<Example> mExampleList;
private int mWordNumber;
//callback interface
private TranslateModeChangeListener mWordPartFragments;
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mWordPartFragments = (TranslateModeChangeListener) context;
} catch (ClassCastException ex) {
throw new ClassCastException("Must implement WordPartFragments interface");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_word_example, container, false);
ButterKnife.bind(this, view);
mWordInfoList = WordActivity.sWordInfoList;
mWordNumber = WordActivity.sWordNumber;
mExampleList = mWordInfoList.get(mWordNumber).getExamples();
showTranslation();
mShowTranslateSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//this method is called from activity=> callback interface
mWordPartFragments.changeTranslateMode(b);
showTranslation();
}
});
return view;
}
//this method is called when viewpager shows this fragment and it is visible to user
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
showTranslation();
}
}
//this methoud updates my UI: shows or hides the translation
public void showTranslation() {
if (isAdded()) {
boolean showTranslation = WordActivity.sTranslationShown;
//Log.e("Ex", "added & shown = " + showTranslation);
mShowTranslateSwitch.setChecked(showTranslation);
mExample1ContentFaTV.setVisibility((showTranslation) ? View.VISIBLE : View.INVISIBLE);
}
}
}
I've 2 fragments in viewpager and I want to add callback methods using interface in both. I add the interface listener while initiating fragments in viewpager adapter but only the last fragment's is being called. That's why when I click on the MainActivity's menu option, only the Toast in MyFragB is being called even if MyFragA is showing.
Both Fragments... Only Activity calling MyFragB Toast is showing when wither fragment is opened
public class MyFragA extends Fragment implements FragmentCaller {
private TextView myTxt;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.myfraga, container, false);
}
#Override
public void CallFragment() {
if(getActivity()!=null)
Toast.makeText(getActivity(), "Activity calling MyFragA", Toast.LENGTH_SHORT).show();
}
}
public class MyFragB extends Fragment implements FragmentCaller{
private TextView myTxt;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.myfragb, container, false);
}
#Override
public void CallFragment() {
if(getActivity()!=null)
Toast.makeText(getActivity(), "Activity calling MyFragB", Toast.LENGTH_SHORT).show();
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
TabLayout tabs;
ViewPager viewpager;
FragmentCaller fragListerner = null;
public interface FragmentCaller {
void CallFragment();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (TabLayout)findViewById(R.id.tabs);
viewpager = (ViewPager)findViewById(R.id.viewpager);
SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(this, getSupportFragmentManager());
viewpager.setAdapter(adapter);
tabs.setupWithViewPager(viewpager);
} // onCreate ends
public class SimpleFragmentPagerAdapter extends FragmentStatePagerAdapter {
private Context mContext;
public SimpleFragmentPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
// This determines the fragment for each tab
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position == 0) {
fragment = new MyFragA();
fragListerner = (FragmentCaller) fragment;
return fragment;
} else if (position == 1){
fragment = new MyFragB();
fragListerner = (FragmentCaller)fragment;
return fragment;
}
return null;
}
// This determines the number of tabs
#Override
public int getCount() {
return 2;
}
// This determines the title for each tab
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
switch (position) {
case 0:
return mContext.getString(R.string.fraga);
case 1:
return mContext.getString(R.string.fragb);
default:
return null;
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.callback, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.call:
if(fragListerner!=null){
if(fragListerner instanceof MyFragA){
fragListerner.CallFragment();
}else if(fragListerner instanceof MyFragB){
fragListerner.CallFragment();
}
}
break;
}
return true;
}
}
I used rick's answer from here.
public class MainActivity extends AppCompatActivity {
TabLayout tabs;
ViewPager viewpager;
public static int currentFrag=0;
SimpleFragmentPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (TabLayout)findViewById(R.id.tabs);
viewpager = (ViewPager)findViewById(R.id.viewpager);
adapter = new SimpleFragmentPagerAdapter(this, getSupportFragmentManager());
viewpager.setAdapter(adapter);
tabs.setupWithViewPager(viewpager);
viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
System.out.println("sammy_current_position: "+position);
currentFrag = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
} // onCreate ends
public class SimpleFragmentPagerAdapter extends FragmentStatePagerAdapter {
private Context mContext;
public SimpleFragmentPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new MyFragA();
} else if (position == 1){
return new MyFragB();
}
return null;
}
#Override
public int getCount() {
return 2;
}
// This determines the title for each tab
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
switch (position) {
case 0:
return mContext.getString(R.string.fraga);
case 1:
return mContext.getString(R.string.fragb);
default:
return null;
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.callback, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.call:
if(currentFrag == 0) {
MyFragA frag1 = (MyFragA)viewpager.getAdapter().instantiateItem(viewpager, viewpager.getCurrentItem());
frag1.specialCase();
}
break;
}
return true;
}
}
but only the last fragment's is being called
Of Course ! because at pos == 0 you are setting fragListerner = (FragmentCaller) fragment then at again in pos == 1 you re-set fragListerner = (FragmentCaller)fragment;. So this condition, fragListerner instanceof MyFragB will always be true!
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position == 0) {
fragment = new MyFragA();
fragListerner = (FragmentCaller) fragment;
return fragment;
} else if (position == 1){
fragment = new MyFragB();
fragListerner = (FragmentCaller)fragment;
return fragment;
}
return null;
}
So, you are trying to communicate from activity to fragment
okay, if you still want to use interfaces, you can do it like that:
create an instance of your interface for each fragment! and in getItem assign them both,
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position == 0) {
fragment = new MyFragA();
fragAListerner = (FragmentCaller) fragment;
return fragment;
} else if (position == 1){
fragment = new MyFragB();
fragBListerner = (FragmentCaller)fragment;
return fragment;
}
return null;
}
But, there is an easier way to call fragment's methods from it's parent activity, which is like follows, for ex:
Fragment fragment = adapter.getItem(0); // MyFragA is at pos 0
fragment.<specific_function_name>();
Or, by using it's id!
MyFragA fragment = (MyFragA) getFragmentManager().findFragmentById(R.id.MyFragAId);
fragment.<specific_function_name>();
Or, by using it's tag!
MyFragA fragment = (MyFragA) getFragmentManager().findFragmentByTag("MyFragATag");
fragment.<specific_function_name>();
I have faced this issue, maybe there is already the same issue, but I cannot find in this page. So my problem is that I have my activity, which initialize ViewPager and I have 2 fragments in this viewpager.
My Activity:
public class ShoppingDetailsActivity extends BaseActivity {
ViewPagerAdapter adapter;
#Bind(R.id.view_pager)
ViewPager viewPager;
#Bind(R.id.pager_tabs)
PagerSlidingTabStrip pagerSlidingTabStrip;
int shop_id;
int id;
int shop_sub_id;
int subId;
int shop_sub_sub_id;
int subSubId;
int shop_detail_id;
int detailId;
public static final String SHOP_ID = "shop_id";
public static final String SHOP_SUB_ID = "shop_sub_id";
public static final String SHOP_SUB_SUB_ID = "shop_sub_sub_id";
public static final String SHOP_DETAIL_ID = "shop_detail_id";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityComponent().inject(this);
setContentView(R.layout.activity_shopping_details);
ButterKnife.bind(this);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
pagerSlidingTabStrip.setViewPager(viewPager);
shop_id = getIntent().getIntExtra(SHOP_ID, id);
shop_sub_id = getIntent().getIntExtra(SHOP_SUB_ID, subId);
shop_sub_sub_id = getIntent().getIntExtra(SHOP_SUB_SUB_ID, subSubId);
shop_detail_id = getIntent().getIntExtra(SHOP_DETAIL_ID, detailId);
}
}
My Adapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new InfoAdminFragment();
break;
case 1:
fragment = new ViewAdminFragment();
break;
default:
break;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "InfoAdminFragment";
} else if (position == 1) {
return "ViewAdminFragment";
} else {
return super.getPageTitle(position);
}
}
}
As you can see in My Activity I have a lot of IDs using getIntent() and get them successfully, but I also need somehow to pass to my both fragments in ViewPager, how can I make solve this issue?
Pass the ID's as bundle to ViewPager adapter from your activity
adapter = new ViewPagerAdapter(getSupportFragmentManager(), getIntent().getExtras());
Modify your ViewPager adapter as below
public class ViewPagerAdapter extends FragmentPagerAdapter {
private Bundle bundle;
public ViewPagerAdapter(FragmentManager fm, Bundle bundle) {
super(fm);
this.bundle = bundle;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new InfoAdminFragment();
break;
case 1:
fragment = new ViewAdminFragment();
break;
default:
fragment = new InfoAdminFragment();
break;
}
fragment.setArguments(bundle);
return fragment;
}
//other code
}
And retrieve the bundle in your fragments
Bundle bundle = getArguments();
shopId = bundle.getInt(ShoppingDetailsActivity.SHOP_ID);
Check your code with this one:
private int shop_id;
private int shop_sub_id;
private int shop_sub_sub_id;
private int shop_detail_id;
public void setExtraData(int shopId, int shopSubId, shopSubSubId, shopDetailId) {
this.shop_id = shopId;
this.shop_sub_id = shopSubId;
this.shop_sub_sub_id = shopSubSubId;
this.shop_detail_id = shopDetailId;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new InfoAdminFragment();
break;
case 1:
fragment = new ViewAdminFragment();
break;
default:
break;
}
setBundleData(fragment);
return fragment;
}
public void setBundleData(Fragment fragment){
Bundle bundle = new Bundle();
bundle.putInt("shop_id", shop_id);
bundle.putInt("shop_sub_id", shop_sub_id);
bundle.putInt("shop_sub_sub_id", shop_sub_sub_id);
bundle.putInt("shop_detail_id", shop_detail_id);
fragment.setArguments(bundle);
}
And in your activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityComponent().inject(this);
setContentView(R.layout.activity_shopping_details);
ButterKnife.bind(this);
shop_id = getIntent().getIntExtra(SHOP_ID, id);
shop_sub_id = getIntent().getIntExtra(SHOP_SUB_ID, subId);
shop_sub_sub_id = getIntent().getIntExtra(SHOP_SUB_SUB_ID, subSubId);
shop_detail_id = getIntent().getIntExtra(SHOP_DETAIL_ID, detailId);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.setExtraData(shop_id, shop_sub_id, shop_sub_sub_id, shop_detail_id);
viewPager.setAdapter(adapter);
pagerSlidingTabStrip.setViewPager(viewPager);
}
In your fragment you can get:
getArguments().getInt(/*Key*/, /*Default value*/);
like:
getArguments().getInt("shop_id", -1);
You can achieve the same above scenario by passing intent rather than single-single values as I am doing here in setExtraData method of adapter.
My objective is to replace the Fragment inside viewpager. I got a matching solution for the same Replace one fragment with other
Below is the code i am using almost same from the above link
public interface SecondPageFragmentListener {
void onSwitchToNextFragment();
}
I have implemented the above interface in my ViewPager Adapter.I am just pasting my full Code for the Adapter so it easy to understand it for everyone
public class TabPagerAdapter extends FragmentPagerAdapter{
private final Resources resources;
private Context mContext;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
Fragment result = null;
FirstPageListener listener = new FirstPageListener();
public TabPagerAdapter(final Resources resources, FragmentManager fm,Context mContext) {
super(fm);
this.mContext = mContext;
this.resources = resources;
}
public void updateData(){
notifyDataSetChanged();
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// First Fragment of First Tab
result = new Position();
break;
case 1:
// First Fragment of Second Tab
result = new Alerts();
break;
case 2:
// First Fragment of Third Tab
result = new Reports();
break;
default:
result = null;
break;
}
return result;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(final int position) {
switch (position) {
case 0:
return resources.getString(R.string.tab_position_title);
case 1:
return resources.getString(R.string.tab_alert_title);
case 2:
return resources.getString(R.string.tab_reports_title);
default:
return null;
}
}
#Override
public int getItemPosition(Object object)
{
if (object instanceof Alerts &&
result instanceof CaptureIncident) {
return POSITION_NONE;
}
if (object instanceof CaptureIncident &&
result instanceof Alerts) {
return POSITION_NONE;
}
return POSITION_UNCHANGED;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
private final class FirstPageListener implements
SecondPageFragmentListener {
public void onSwitchToNextFragment() {
((AppCompatActivity)mContext).getSupportFragmentManager().beginTransaction().remove(result)
.commit();
if (result instanceof Alerts){
result = CaptureIncident.newInstance("","",listener);
}else{ // Instance of NextFragment
result = Alerts.newInstance("","",listener);
}
notifyDataSetChanged();
}
}
}
I have just created a Inner class and implemented my SecondPageFragmentListener interface as mentioned in the link.
Now I have init the interface in my Alert Fragment
static SecondPageFragmentListener secondPageListener;
public static Alerts newInstance(String param1, String param2,SecondPageFragmentListener listener) {
Alerts fragment = new Alerts();
secondPageListener = listener;
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
Now I am calling the interface method on button click
secondPageListener.onSwitchToNextFragment();
Below is My Fragment Code
public class Alerts extends RootFragment{
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private RecyclerView gridview;
private GridAdapter gridAdapter;
private GridLayoutManager gridLayoutManager;
private OnFragmentInteractionListener mListener;
public static SecondPageFragmentListener secondPageListener;
public Alerts() {
// Required empty public constructor
}
#SuppressLint("ValidFragment")
public Alerts(SecondPageFragmentListener listener){
secondPageListener = listener;
}
public static Alerts newInstance(String param1, String param2,SecondPageFragmentListener listener) {
Alerts fragment = new Alerts();
secondPageListener = listener;
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_alerts, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initUiView();
RecyclerListener();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void initUiView() {
gridview = (RecyclerView)getActivity().findViewById(R.id.gridview);
gridview.setHasFixedSize(true);
gridview.setLayoutManager(new GridLayoutManager(getActivity(), 3));
//list Population
List<ItemObject> rowListItem = getAllItemList();
gridAdapter = new GridAdapter(getActivity(),rowListItem);
gridview.setAdapter(gridAdapter);
gridAdapter.notifyDataSetChanged();
}
private List<ItemObject> getAllItemList(){
List<ItemObject> allItems = new ArrayList<ItemObject>();
allItems.add(new ItemObject("altercation","0,50 miles - 10 min ago", R.drawable.altercation));
allItems.add(new ItemObject("offence","0,25 miles - 45 min ago", R.drawable.offence));
allItems.add(new ItemObject("harassment","0,60 miles - 1h ago", R.drawable.harassment));
allItems.add(new ItemObject("doubt","0,5 miles - 48 min ago", R.drawable.doubt));
allItems.add(new ItemObject("incident","0,50 miles - 30 min ago", R.drawable.incident));
return allItems;
}
private void RecyclerListener(){
gridview.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), gridview, new ItemClickListener(){
#Override
public void onClick(View view, int position) {
Alerts.secondPageListener.onSwitchToNextFragment();
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
}
But it showing me the error
java.lang.NullPointerException
at
com.oxilo.mrsafer.fragement.Alerts$1.onClick(Alerts.java:173)
The error indicates that secondpagelitener is null.
Please help me to resolve the issue.
Also on the below link
Replace one fragment with other
he implement the same interface in Fragment too as he already implemented
the interface in view pager adapter. so why he is implementing in the Fragment too.From my understanding it wrong but please correct me if i am wrong.
you can try this. for tab2 fragment create xml file like this:
<FrameLayout 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:id="#+id/main"> <!-- this line is the most important part-->
<!-- your other layout s or views go here-->
</FrameLayout>
or just set id to your topest layout in you frag xml and and use it as container id in java code.
then in your fragment code in where you try to call interface to switch fragment just do that:
getChildFragmentManager().beginTransaction().replace(R.id.main, destfragment).addToBackStack("youtag").commit();
You are calling this code
public void onSwitchToNextFragment() {
((AppCompatActivity)mContext).getSupportFragmentManager().beginTransaction().remove(result).commit();
if (result instanceof Alerts){
result = CaptureIncident.newInstance("","",listener);
} else{ // Instance of NextFragment
result = Alerts.newInstance("","",listener);
}
notifyDataSetChanged();
}
From object created here:
case 1:
// First Fragment of Second Tab
result = new Alerts();
break;
so secondPageListener is not initialized yet. You can try to create change your code to this:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// First Fragment of First Tab
result = new Position();
break;
case 1:
// First Fragment of Second Tab
result = Alerts.newInstance("","",listener); // This line is important
break;
case 2:
// First Fragment of Third Tab
result = new Reports();
break;
default:
result = null;
break;
}
return result;
}
EDIT
If it's going to be static then you can try this:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// First Fragment of First Tab
result = new Position();
break;
case 1:
// First Fragment of Second Tab
result = Alerts.newInstance("","",listener); // This line is important
Alerts.secondPageListener = listener;
break;
case 2:
// First Fragment of Third Tab
result = new Reports();
break;
default:
result = null;
break;
}
return result;
}
Also make sure to call it like this in your onClick
Alerts.secondPageListener.onSwitchToNextFragment();
I'm using the MainActivity's SearchView here to filter the listview which is showing under tabs but there is an issue of the state of Fragment.
It filters perfectly but when I select first Tab(ADVISORY), then it filters the child of this Tab. And after selecting next Tab(TOP ADVISORY), it filters all listview of the child of this tab but it stops filtering in previous Tab (ADVISORY). And at last I move to the EXPERTVIEW it works only for it not for others.
After lots of debugging I found that it doesn't get destroy when we select another Parent Tab so now I wanna know how I can remove a fragment from its adapter on unselected and reselect on selected again.
MainTabFragment.java
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1, index = 0;
int position_tab = 0;
Bundle args;
int Current_tab = 0;
public static MyTabLayout myTabLayout;
private static MainTabFragment sMainTabFragment;
public static NonSiwpablePager pager;
private Fragment mFragment;
SharedPreferences pref;
private static final int NUM_ITEMS = 2;
List<Integer> TABLE;
public MainTabFragment() {
// Required empty public constructor
}
public static MainTabFragment getInstance() {
return sMainTabFragment;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
pager = (NonSiwpablePager) view.findViewById(R.id.pager);
final ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
pager.setOffscreenPageLimit(NUM_ITEMS-1);
changeTab();
final Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null) {
pager.setCurrentItem(position_tab);
}
index = pager.getCurrentItem();
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
// ViewPagerAdapter adapter = ((ViewPagerAdapter)pager.getAdapter());
final Fragment fragment22 = mAdapter.getRegisteredFragment(pager.getCurrentItem());
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
myTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
// mAdapter.destroyAllItem();
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
return view;
}
public void changeTab() {
Current_tab = pager.getCurrentItem();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
public void setCurrentItem(int item) {
pager.setCurrentItem(item);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
AdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
TopAdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
ExperViewPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
private Fragment mCurrentFragment;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
#Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
#Override
public Fragment getItem(int position) {
Log.e("Fragmentss", (Fragment) maps.get(position).get(KEY_FRAGMENT) + "");
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (mCurrentFragment != object) {
mCurrentFragment = (Fragment) object;
}
super.setPrimaryItem(container, position, object);
}
#Override
public int getCount() {
return maps.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
}