Hide a Floating Action Button of another Layout

…衆ロ難τιáo~ 提交于 2019-12-04 04:02:29

First of all, change your line

final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fabBtn);

to

fabBtn = (FloatingActionButton)findViewById(R.id.fabBtn);


Solution #1 - get view (if you need object)

Then, in your MainActivity add getter for your FloatingActionButton, like

public FloatingActionButton getFloatingActionButton {
    return fabBtn;
}

Finally, in your Fragment call:

FloatingActionButton floatingActionButton = ((MainActivity) getActivity()).getFloatingActionButton();

and

if (floatingActionButton != null) {
    floatingActionButton.hide();
}

or

if (floatingActionButton != null) {
    floatingActionButton.show();
}


Solution #2 - add two methods in MainActivity (if you need only specific methods, like show() / hide())

public void showFloatingActionButton() {
     fabBtn.show();
};

public void hideFloatingActionButton() {
     fabBtn.hide();
};

And in your Fragment call to hide:

((MainActivity) getActivity()).hideFloatingActionButton();

or to show:

((MainActivity) getActivity()).showFloatingActionButton();


Note

If you use more than one Activity, you must check if it's proper Activity:

if (getActivity() instanceof MainActivity) {
    getActivity().yourMethod(); // your method here
}

In your fragment your rootView layout is not main layout and you cannot expect the rootView will return the fab button. Thats why you are getting null pointer exception

You better use interface to detect page scrolling and controll it via your activity

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