问题
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