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

空扰寡人 提交于 2019-12-14 04:16:12

问题


I am working or an app where I have 4 fragments in viewpager and floating action button (fab). When I click on fab there appear 3 subfabs. Each of them start different activities where user can search data from different fragments. Is it possible to set fab so that if I click on it while I'm in first fragment it'll open an activity for searching inside this fragment, onClick inside second - search for second and etc. The issue is that now clicking on sub fab while I'm in some fragment I can search data from another fragment too and it's a bit weird. I understand question is kinda strange, if something is unclear I'll explain further


回答1:


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
        }
    });
}



回答2:


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.



来源:https://stackoverflow.com/questions/33516130/is-it-possible-to-set-different-actions-for-floating-action-button-in-differet-f

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