Is it possible to set different actions for floating action button in differet fragments?

天涯浪子 提交于 2019-12-03 17:29:24

You can make FAB button public and implement onClick listener in each fragment. You should override setUserVisibleHint and put your code onResume so getActivity() will not return null. Fab button will have different actions in different fragments.

Here's an example, inside each fragment when you want Fab click listener:

@Override
public void setUserVisibleHint(boolean visible)
{
    super.setUserVisibleHint(visible);
    if (visible && isResumed())
    {            
        onResume();
    }
}

 @Override
public void onResume()
{
    super.onResume();
    if (!getUserVisibleHint())
    {
        return;
    }

    MainActivity mainActivity = (MainActivity)getActivity();
    mainActivity.fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          //Do what you want
        }
    });
}

You can check in onclick method of floating action button which fragment is currently opened and calling it.

Call findFragmentById() on FragmentManager and determine which fragment is in your R.id.frameTitle container.

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