getSupportActionBar from inside of Fragment ActionBarCompat

前端 未结 6 946
梦毁少年i
梦毁少年i 2020-12-07 11:45

I\'m starting a new project that uses the AppCompat/ActionBarCompat in v7 support library. I\'m trying to figure out how to use the getSuppor

6条回答
  •  无人及你
    2020-12-07 12:07

    in your fragment.xml add Toolbar Tag from support library

     
    

    Now how we can control it from MyFragment class? let's see

    inside onCreateView function add the following

    mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
    ((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
    
    //add this line if you want to provide Up Navigation but don't forget to to 
    //identify parent activity in manifest file
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    

    and if you want to add items to the toolbar within MyFragment you must add this line inside onCreateView function

            setHasOptionsMenu(true);
    

    this line is important, if you forget it, android will not populate your menu Items.

    assume we identify them in menu/fragment_menu.xml

    after that override the following functions

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.fragment_menu, menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.action_1:
                // do stuff
                return true;
    
            case R.id.action_2:
                // do more stuff
                return true;
        }
    
        return false;
    }
    

    hope this helps

提交回复
热议问题