Menu use

First, add a menu folder in the folder res

Second, add menu xml file in the folder menu

 

 

 Third, add two menu items in the menu file

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/add_item"
        android:title="Add"/>
    <item
        android:id="@+id/remove_item"
        android:title="Remove"/>
</menu>

Four, MainActivity override the onCreateOptionsMenu () method. This interface can be displayed on the menu

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

V. rewrite onOptionsItemSelected () method. Able to respond to a click event

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.add_item:
                Toast.makeText(this, "You clicked Add", Toast.LENGTH_SHORT).show();
                break;
            case R.id.remove_item:
                Toast.makeText(this, "You clicked Remove", Toast.LENGTH_SHORT).show();
                break;
            default:
        }
        return true;
    }

Six, can be a normal run. Note: menu is a separate xml file, not written in the Layout file.

 

Guess you like

Origin www.cnblogs.com/xxie12/p/11469413.html