Menu

Benefits of using XML files to define menu resources

1. It is helpful to observe the menu structure

2. Separation of menu resources and logic code, which is conducive to maintenance

3. Menu resources can be used by different platforms, versions, etc.


How to create the Menu menu:

First, use XML to create:

1. Right-click on res->New->Android resource directory

2. After clicking, the Resource type as shown in the figure below appears and select menu, the name can be selected, click ok

3. You can see that the menu has appeared in the menu bar

4. Right-click on the menu and select as shown below:

5. The file name can be started by yourself, click ok

6. You can see that there is a main.XML file in the menu folder, and main is the file name I made

7. Open the main.XML file and write the code in it:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/font_group"
        android:title="Set font size"
        android:orderInCategory="3">
    </item>
    <item android:id="@+id/action_color"
        android:title="Set font color"
        android:orderInCategory="1">
    </item>
    <item android:id="@+id/action_style"
        android:title="Set font style"
        android:orderInCategory="2">
    </item>
</menu>
<!--
    android:id="@+id/font_group" Set the unique identifier of the current menu item
    android:title="Set font size" Set the text of the menu item
    android:orderInCategory="3" Sets the order of menu items of the same category
-->

8. Open the Activity.java file and reload the onCreate() function in it


import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

/**
 * Demonstrate the use of OptionMenu
 */
public class MainActivity extends AppCompatActivity  {

    private TextView tvShow;
    private float fontSize=20.0f;
    private static final int ITEMID=4;//ID of menu item
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);
        tvShow=findViewById(R.id.tv_show);
        tvShow.setTextSize(fontSize);//Set the initial font size in textView
    }

    /**
     * Indicates the use of a callback when the activity creates an options menu
     * @param menu
     * @return
     * true to show menu items
     * false can't show menu items
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        MenuInflater inflater = getMenuInflater();
//        inflater.inflate(R.menu.main,menu);
        //The first way to create a menu, xml file
        getMenuInflater().inflate(R.menu.main,menu); //The first parameter is the resource file, and the second parameter is the menu object
    }

    /**
     * Represents the method to call back when the item in the options menu is selected
     * @param item represents the menu item object
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();//Get the resource id of the currently clicked menu item
        switch (itemId){
            case R.id.font_group://click to set font size
                fontSize += 5;
                tvShow.setTextSize(fontSize);
                break;
            case R.id.action_color://click to set font color
                // randomly generate colors
                int red = (int) (Math.random()*256);
                int green = (int) (Math.random()*256);
                int blue = (int) (Math.random()*256);
                tvShow.setTextColor(Color.rgb(red,green,blue));
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

9. The code of activity_main is as follows

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <TextView
        android:id="@+id/tv_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set font"
        android:textSize="20dp"/>
</RelativeLayout>

Second, the method of adding menu using Java code

.activity_main remains the same as above

Add the following code to the onCreateOptionsMenu() method of the Java code to dynamically add the corresponding menu items to the Menu menu

        //add(groupId menu item grouping, ItemId menu item unique identifier id, order represents the order of menu items, the text displayed by the menu item)
        menu.add(Menu.NONE,ITEMID,Menu.NONE,"Set font");

The Java file code is as follows:
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

/**
 * Demonstrate the use of OptionMenu
 */
public class MainActivity extends AppCompatActivity  {

    private TextView tvShow;
    private float fontSize=20.0f;
    private static final int ITEMID=4;//ID of menu item
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);
        tvShow=findViewById(R.id.tv_show);
        tvShow.setTextSize(fontSize);//Set the initial font size in textView
    }

    /**
     * Indicates the use of a callback when the activity creates an options menu
     * @param menu
     * @return
     * true to show menu items
     * false can't show menu items
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //add(groupId menu item grouping, ItemId menu item unique identifier id, order represents the order of menu items, the text displayed by the menu item)
        menu.add(Menu.NONE,ITEMID,Menu.NONE,"Set font");
        return true;
    }

    /**
     * Represents the method to call back when the item in the options menu is selected
     * @param item represents the menu item object
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //The usage in this method can refer to the implementation method of the above xml writing method.
        return super.onOptionsItemSelected(item);
    }
}

Three, let Activity inherit the method of Activity

Change the AppCompatActivity that the Activity originally inherited to the inherited Activity

Override the onMenuItemSelected method

/**
 * Represents the method of the clicked callback in the menu item
 * @param featureId
 * @param item
 * @return
 */
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    int itemId = item.getItemId();
    if(itemId==ITEMID){
        tvShow.setText("Called the second click event of the menu item");
    }
    return super.onMenuItemSelected(featureId, item);
}

Some children will ask, what is the ITEMID of if (itemId==ITEMID), in fact, this value can be directly filled in a menu item ID, and ITEMID is written here because the complete code is written above, private static final int ITEMID=4;//The ID of the menu item

Fourth, the fourth way to handle menu items, add listening events in the onCreateOptionsMenu() method

/**
     * Indicates the use of a callback when the activity creates an options menu
     * @param menu
     * @return
     * true to show menu items
     * false can't show menu items
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem item=menu.findItem(R.id.action_style);
        item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(MainActivity.this,item.getTitle().toString(),Toast.LENGTH_LONG).show();
                return false;
            }
        });
        return true;
    }

Submenus can also be added to the menu, such as under the menu file main

    <item android:id="@+id/font_group"
        android:title="Set font size"
        android:orderInCategory="3">
        <!--Settings submenu-->
        <item android:id="@+id/action_add" android:title="增大字体"></item>
        <item android:id="@+id/action_sub" android:title="减小字体"></item>
    </item>

So how to get the binding event for the submenu?

Directly in the method of binding event monitoring (such as onOptionsItemSelected() method), find the corresponding resource ID.

            case R.id.action_add:
                fontSize += 5;
                tvShow.setTextSize(fontSize);
                break;

Attach the complete Java code

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Demonstrate the use of OptionsMenu
 */
public class MainActivity extends Activity {
    private TextView tvShow;
    private float fontSize=20.0f;
    private static final int ITEMID=4;//Menu item id
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);
        tvShow= (TextView) findViewById(R.id.tv_show);
        tvShow.setTextSize(fontSize);//Set the initial font size in textview
    }

    /**
     * Represents the method that is called back when the activity creates the options menu
     * @param menu
     * @return
     * true to show menu items
     * false can't show menu items
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Get the menu filler object
        // MenuInflater inflater=getMenuInflater();
        // inflater.inflate(R.menu.main,menu);

        //The first way to create a menu xml file
        getMenuInflater().inflate(R.menu.main,menu);

        //The first way to create a menu code
        // add(groupId menu item grouping, ItemId menu item unique identifier id, order indicates the ordering of menu items
        // , the text displayed by the menu item)
        menu.add(Menu.NONE,ITEMID,Menu.NONE,"Set font");

        //The third way to handle the menu item click event
        MenuItem item=menu.findItem(R.id.action_style);
        item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(MainActivity.this,item.getTitle().toString(),Toast.LENGTH_SHORT).show();
                return false;
            }
        });
        return true;
    }

    /**
     * Represents the method to call back when the item in the options menu is selected
     * @param item represents the menu item object
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId=item.getItemId();//Get the resource id of the currently clicked menu item
        switch (itemId){
            case R.id.action_add://click to set font size
                fontSize+=5;
                tvShow.setTextSize(fontSize);
                break;
            case R.id.action_sub:
                fontSize-=5;
                tvShow.setTextSize(fontSize);
                break;
            case R.id.action_color://click to set font color
                // randomly generate colors
                int red= (int) (Math.random()*256);
                int green= (int) (Math.random()*256);
                int blue= (int) (Math.random()*256);
                tvShow.setTextColor(Color.rgb(red,green,blue));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Represents the method of the clicked callback in the menu item
     * @param featureId
     * @param item
     * @return
     */
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        int itemId=item.getItemId();
        if(itemId==ITEMID){
            tvShow.setText("Called the second click event of the menu item");
        }
        return super.onMenuItemSelected(featureId, item);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325936313&siteId=291194637