Different implementation for a floating action button in each fragment of an activity

杀马特。学长 韩版系。学妹 提交于 2019-12-05 08:55:35

Not sure if this'll work with SlidingTabLayout since I use ViewPager.

Have the FAB onClick call a method (e.g. onFABClick() ) in your activity and define it as:

public void onFABClick(View view) {
    if (fragments.get(mViewPager.getCurrentItem()) instanceof FragmentA) {
      if (fragmentA!= null) {
        fragmentA.fabOnClick();
      }
    } else if (fragments.get(mViewPager.getCurrentItem()) instanceof FragmentB) {
      if (fragmentB!= null) {
        fragmentB.fabOnClick();
      }
    }
  }

Here fragments is the array that holds fragment objects. It is the array that is passed to the adapter of the ViewPager. I guess you'll have to change mViewPager.getCurrentItem() with the equivalent get index of current fragment method of SlidingTabLayout.

Lastly, the fabOnClick() method is implemented in each fragment. (You'll need to have all your fragments implement an interface (e.g. FABActionInterface) and add the method signature there.

Here you are basically catching the FAB onclick and directing it to call a method on the current fragment.

So, each of your fragments should implement View.OnClickListener interface.

And in your activity, your viewpager should implement OnPageChangeListener, like this:

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            View.OnClickListener listener = (View.OnClickListener) adapter.getItem(position);
            fab.setOnClickListener(listener );
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

In this case, your FAB will do its work in proper way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!