user1324887 user1324887 - 4 months ago 25
Android Question

Both Fragment in ActionBar return true for fragment.isVisible()

In my

MainActivity
with
ActionBar
I listen to a listener from a
DialogFragment
and based on which Fragment of
ActionBar
i am on, I need to do some things.

I am using below code to get the current fragment and check which of the two
ActionBar
fragment i am on:

private Fragment getVisibleFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment != null && fragment.isVisible())
return fragment;
}
}
return null;
}


but
fragment.isVisible()
returns true for both the fragments. Why would that be? Is there another flag I need to consider?

Below is my
FragmentPagerAdapter
implentation:

public class SectionsPagerAdapter extends FragmentPagerAdapter {
Context context;
public SectionsPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}

@Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new ReceivedListFragment();
case 1:
return new SentListFragment();
}
return null;
}

@Override
public int getCount() {
// Show 2 total pages.
return 2;
}

@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return context.getString(R.string.title_section1).toUpperCase(l);
case 1:
return context.getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}

Answer

It seems you are using a ViewPager and you need to find out which is the currently selected view. The problem in your approach, in my opinion, is that the viewpager keeps instance of at least two fragments. It seems you have two fragments only, both of the fragments are kept by the viewpager and which is why you get the isVisible true for both the fragments.

If your only need is to get the currently selected fragment on the viewpager, please try this method from the viewpager class:

mViewPagerInstance.getCurrentItem();

which will give you the currently selected fragment index.

Another way would be to add a PageChangeListener for your viewpager and then listen to page change events:

class MyActivity extends Activity{
  private int curPage;

  private static class MFragChangeListener extends SimpleOnPageChangeListener{
        public void onPageSelected(int position) {
               curPage = position;
  }
} 

  ........... /* Rest of your code */

mViewPagerInstance.setOnPageChangeListener(new MFragChangeListener());
/* Now access curPage to get the current selected page index whenever you need it. */

Please refer to this SO post as well.

Comments