How to get Toolbar from fragment?

后端 未结 10 1854
梦毁少年i
梦毁少年i 2020-11-28 01:45

I have ActionBarActivity with NavigationDrawer and use support_v7 Toolbar as ActionBar. In one of my fragments toolbar has custom view

10条回答
  •  悲&欢浪女
    2020-11-28 02:23

    if you are using custom toolbar or ActionBar and you want to get reference of your toolbar/action bar from Fragments then you need to first get instance of your Main Activity from Fragment's onCreateView Method like below.

    MainActivity activity = (MainActivity) getActivity();
    

    then use activity for further implementation like below

    ImageView vRightBtn = activity.toolbar.findViewById(R.id.toolbar_right_btn);
    

    Before calling this, you need to initialize your custom toolbar in your MainActivity as below.

    First set define your toolbar public like

    public Toolbar toolbar;
    public ActionBar actionBar;
    

    and in onCreate() Method assign the custom toolbar id

    toolbar = findViewById(R.id.custom_toolbar);
    setSupportActionBar(toolbar);
    actionBar = getSupportActionBar();
    

    That's It. It will work in Fragment.

提交回复
热议问题