Dawn Impulse Dawn Impulse - 1 month ago 8
Android Question

How to hide FAB on a particular fragment

Well I want to remove/hide FAB only on a particular fragment , HISTORY tab in my case .

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
.... (Overriding methods , I didnt do anything here
});


My methods for inflating View Pager

private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new HistoryFragment(), "HISTORY");
adapter.addFragment(new TransactionFragment(), "CURRENT");
adapter.addFragment(new FutureFragment(), "FUTURE");

viewPager.setAdapter(adapter);

}

class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
super(manager);

}

@Override
public android.support.v4.app.Fragment getItem(int position) {
return mFragmentList.get(position);
}

@Override
public int getCount() {
return mFragmentList.size();
}

public void addFragment(android.support.v4.app.Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}

@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}


Where and how should I make changes to my code to Hide my FAB from the HISTORY tab/fragment and show again on other Tabs

Answer

I'd think it's as simple as this:

viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            if(position == 0) {
               // hide FAB
            } else {
               // show FAB
            }
        }
}

You can do a lot of cleanup to improve maintenance like assign page numbers to each page like:

private static final int PAGE_HISTORY = 0;
private static final int PAGE_TRANSACTION = 1;
private static final int PAGE_FUTURE = 2;

So instead of if(position == 0) you say if(position == PAGE_HISTORY). That way you don't have to change a lot of code if you ever change your pages around.

Comments