Handling activity toolbar visibility according to visible fragment

社会主义新天地 提交于 2019-12-11 17:50:38

问题


In my android application I have one activity and many fragments. However, I only want to show the toolbar for some fragments, for the others I want the fragment to be fullscreen. What's the best and recommended way to do this (show and hide the activity toolbar according to the visible fragment)?


回答1:


I preferred using interface for this.

public interface ActionbarHost {
    void showToolbar(boolean showToolbar);
}

make your activity implement ActionbarHost and override showToolbar as.

@Override
public void showToolbar(boolean showToolbar) {
    if (getSupportActionBar() != null) {
        if (showToolbar) {
            getSupportActionBar().show();
        } else {
            getSupportActionBar().hide();
        }
    }
}

Now from your fragment initialize from onAttach()

private ActionbarHost actionbarHost;
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof ActionbarHost) {
        actionbarHost = (ActionbarHost) context;
    }
}

now just if you want to hide action bar call actionbarHost.showToolbar(false); from fragment.

if (actionbarHost != null) {
            actionbarHost.showToolbar(false);
        }

Also I'd suggest to show it again in onDetach()

@Override
public void onDetach() {
    super.onDetach();
    if (actionbarHost != null) {
        actionbarHost.showToolbar(true);
    }
}



回答2:


Since you want different representations, each of your fragments should have (when you want) their own toolbar.

Hence your Activity's layout will have a simple fragment_container.




回答3:


if you are using viewPager then you can do this using only single toolbar in your MainActivity

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

        }

        @Override
        public void onPageSelected(int position) {

              if(position==YourFragmentPosition)
                        {
                     toolbar.setVisibility(View.VISIBLE);
                           }
                  else{
                      toolbar.setVisibility(View.GONE);
                     }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

    });


来源:https://stackoverflow.com/questions/52466929/handling-activity-toolbar-visibility-according-to-visible-fragment

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