Toolbar used in android Fragment

Can be used directly in Activity

setSupportActionBar(toolbar);

You can override the onCreateOptionsMenu and onoptionsiteselected methods;

But in Fragment, you need to

((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);

In Fragment, you need to change getActivity() to AppCompatActivity to get setSupportActionBar method;

There is also a row to be added in the Fragment

setHasOptionsMenu(true);

To call the onCreateOptionsMenu and onoptionsiteselected methods;

If there is a judgment in the onCreateOptionsMenu method, for example, when changing a state, some menu item s will not be displayed, you can use the following to call the onCreateOptionsMenu method again

getActivity().invalidateOptionsMenu();

Example:

    @Override
    protected void initListener() {
        ((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_edit_select,menu);
        if(showEditSelect){
            menu.findItem(R.id.menu_edit).setVisible(true);
            menu.findItem(R.id.menu_cancel).setVisible(false);
        }else{
            menu.findItem(R.id.menu_edit).setVisible(false);
            menu.findItem(R.id.menu_cancel).setVisible(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            //When you click on an entry, the other one is not displayed
            case R.id.menu_edit:
                showEditSelect = false;
                getActivity().invalidateOptionsMenu();
                break;
            case R.id.menu_cancel:
                showEditSelect = true;
                getActivity().invalidateOptionsMenu();
                break;
        }
        return true;
    }

menu_edit_select.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/menu_edit"
        android:title="edit"
        android:orderInCategory="100"
        app:showAsAction="ifRoom|withText"/>
    <item
        android:id="@+id/menu_cancel"
        android:title="cancel"
        android:orderInCategory="101"
        android:visible="false"
        app:showAsAction="ifRoom|withText"/>
</menu>

Click "Edit" in the title bar menu to display "Cancel" in the original position, and click "Cancel" to display "Edit".

Tags: Android Fragment xml encoding

Posted on Mon, 02 Dec 2019 07:12:44 -0500 by Cugel