Explain the usage of Menu bar

Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Menus are a very important and common part of Android applications. Can greatly save the use of our page space, improve the utilization of the page. There are three common android menus:

  • OptionMenu: Options Menu, the most common Menu in Android, called by the Menu key
  • ContextMenu: the menu that appears after holding down a view component for which the ContextMenu is registered
  • In Android, clicking SubMenu will pop up a hover box showing SubMenu items. SubMenu does not support nesting, that is, it cannot include other submenus

The way menus are defined

  • This is done directly by writing the menu XML file and then calling: getMenuInflater().inflate(R.mu.menu_main, menu); Load the menu
  • Add (group number, ID, sort number, title of menu item), and if the sort number is added in order, fill in 0.

We generally use XML to define Menu, which can reduce code bloat in Java code, and instead of assigning ID with code every time, we only need to modify XML file to modify Menu content, which provides better decoupling, low coupling and high cohesion to a certain extent

We can define menu with three XML elements:

,

, and

:


is a container for menu items. The

element must be the root node of the file and can contain one or more

and

elements.

is the menu item that defines a MenuItem, and you can nest

elements to create submenus.

is an (optional) invisible container for

elements. You can use it to group menu items so that a group of menu items share properties such as availability and visibility.





Where

is our main element, and its common attributes are as follows:

Android :id: unique identifier of a MenuItem android:icon :icon of a MenuItem (optional) android:title :title of a MenuItem (mandatory) android:showAsAction: specifies the display mode of a MenuItem. Commonly used have ifRoom, never, always, withText, can use a | between multiple attributes.

1. OptionMenu

1. Common methods:

// Call OptionMenu, where the menu is initialized and loaded
public boolean onCreateOptionsMenu(Menu menu)
// When a menu item is selected, event handling is complete
public boolean onOptionsItemSelected(MenuItem item)

// This method is called when the menu is closed
public void onOptionsMenuClosed(Menu menu)
// This method is called before the options menu is displayed, where you can adjust the menu (dynamically load the menu list).
public boolean onPrepareOptionsMenu(Menu menu)
// This method is called when the options menu is opened
public boolean onMenuOpened(int featureId, Menu menu)
Copy the code

Example 2.

This is very simple to implement.

Implementation:

The project structure

  1. First create the Menu folder in the RES resource directory, then create a menu folder

The Menu Resource File is named menu_optionmenu.xml


      
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/menu1"
        android:title="Create a group chat"
        android:icon="@drawable/groupchat"/>
    <item
        android:id="@+id/menu2"
        android:title="Add friends/Groups"
        android:icon="@drawable/add"/>
    <item
        android:id="@+id/menu3"
        android:title="Party together."
        android:icon="@drawable/party"/>
    <item
        android:id="@+id/menu4"
        android:title="Sweep it."
        android:icon="@drawable/scan"/>
    <item
        android:id="@+id/menu5"
        android:title="Face to face fast pass"
        android:icon="@drawable/quick_pass"/>
    <item
        android:id="@+id/menu6"
        android:title="Collect and pay"
        android:icon="@drawable/payment"/>
</menu>
Copy the code
  1. Java code
public class MainActivity extends AppCompatActivity {


    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView=findViewById(R.id.text);
    }

    // This method is used to create a display Menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_optionmenu,menu);
        return true;
    }

    // This method is called after the options menu is opened, setting the menu icon display (icon).
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if(menu ! =null) {
            if (menu.getClass().getSimpleName().equalsIgnoreCase("MenuBuilder")) {
                try {
                    Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    method.setAccessible(true);
                    method.invoke(menu, true);
                } catch(Exception e) { e.printStackTrace(); }}}return super.onMenuOpened(featureId, menu);
    }

    // This method listens on the menu item
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        mTextView.setText(item.getTitle());
        switch (item.getItemId()) {
            case R.id.menu1:
                Toast.makeText(this."Click on the number" + 1 + "个", Toast.LENGTH_SHORT).show();
                break;
            case R.id.menu2:
                Toast.makeText(this."Click on the number" + 2 + "个", Toast.LENGTH_SHORT).show();
                break;
            case R.id.menu3:
                Toast.makeText(this."Click on the number" + 3 + "个", Toast.LENGTH_SHORT).show();
                break;
            case R.id.menu4:
                Toast.makeText(this."Click on the number" + 4 + "个", Toast.LENGTH_SHORT).show();
                break;
            case R.id.menu5:
                Toast.makeText(this."Click on the number" + 5 + "个", Toast.LENGTH_SHORT).show();
                break;
        }
        return super.onOptionsItemSelected(item); }}Copy the code

To create our menu in Java code, we simply add it in the onCreateOptionsMenu method using menu’s Add method

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Add parameters (menu item group number, ID, sort number, title)
        menu.add(1.1.1."Create a group chat");
        menu.add(1.1.2."Add friends/Groups");
        menu.add(1.1.3."Party together.");
        menu.add(1.1.4."Sweep it.");
        menu.add(1.1.5."Face to face fast pass");
        menu.add(1.1.6."Collect and pay");
        //getMenuInflater().inflate(R.menu.menu_mian,menu);
        return true;
    }
Copy the code

ContextMenu (ContextMenu)

1. Use steps:

  1. Override the onCreateContextMenu() method
  2. Register the context menu for the View component using the registerForContextMenu() method with view
  3. Override the onContextItemSelected() method to specify event listeners for menu items

Example 2.

Implementation:
  1. Create a new menu_context.xml file under the menu file

      
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <! Define a set of radio buttons -->
    <!-- checkableBehavior的可选值由三个:single设置为单选,all为多选,none为普通选项 -->
    <group android:checkableBehavior="none">
        <item android:id="@+id/blue" android:title="Blue"/>
        <item android:id="@+id/green" android:title="Green"/>
        <item android:id="@+id/red" android:title="Red"/>
        <item android:id="@+id/yellow" android:title="Yellow"/>
    </group>
</menu>
Copy the code
  1. Java code
public class MainActivity extends AppCompatActivity {


    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView=findViewById(R.id.text);

        registerForContextMenu(mTextView);// Register context menu
    }

    // Override the context menu creation method
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        MenuInflater inflator = new MenuInflater(this);
        inflator.inflate(R.menu.menu_context, menu);
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    // Context menu click events
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.blue:
                mTextView.setTextColor(Color.BLUE);
                break;
            case R.id.green:
                mTextView.setTextColor(Color.GREEN);
                break;
            case R.id.red:
                mTextView.setTextColor(Color.RED);
                break;
            case R.id.yellow:
                mTextView.setTextColor(Color.YELLOW);
                break;
        }
        return super.onContextItemSelected(item); }}Copy the code

SubMenu

Submenus are nested in

with another layer

, and can be nested in another layer.

1. Example:

  1. Create menu_sub.xml under the menu file

      
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/colour" android:title="Change color ~">
        <menu>
            <group android:checkableBehavior = "none">
                <item android:id="@+id/colour_blue" android:title="Blue"/>
                <item android:id="@+id/colour_green" android:title="Green"/>
                <item android:id="@+id/colour_red" android:title="Red"/>
                <item android:id="@+id/colour_yellow" android:title="Yellow"/>
            </group>
        </menu>
    </item>
    <item android:id="@+id/font_size" android:title="Change font size ~">
        <menu>
            <group android:checkableBehavior = "none">
                <item android:id="@+id/font_size_10sp" android:title = "10sp"/>
                <item android:id="@+id/font_size_30sp" android:title = "30sp"/>
                <item android:id="@+id/font_size_50sp" android:title = "50sp"/>
                <item android:id="@+id/font_size_70sp" android:title = "70sp"/>
            </group>
        </menu>
    </item>
    <item android:id="@+id/text" android:title="Change text ~">
        <menu>
            <group android:checkableBehavior = "none">
                <item android:id="@+id/text_hello" android:title = "Hello"/>
                <item android:id="@+id/text_menu" android:title = "Menu"/>
                <item android:id="@+id/text_MQ" android:title = "Pennies on the dollar"/>
                <item android:id="@+id/text_div" android:title = "Custom"/>
            </group>
        </menu>
    </item>
</menu>
Copy the code
  1. Java code
public class MainActivity extends AppCompatActivity {


    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView=findViewById(R.id.text);

        registerForContextMenu(mTextView);// Register context menu
    }

    // Override the context menu creation method
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        MenuInflater inflator = new MenuInflater(this);
        inflator.inflate(R.menu.menu_sub, menu);
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    // Context menu click events
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.colour_blue:
                mTextView.setTextColor(Color.BLUE);
                break;
            case R.id.colour_green:
                mTextView.setTextColor(Color.GREEN);
                break;
            case R.id.colour_red:
                mTextView.setTextColor(Color.RED);
                break;
            case R.id.colour_yellow:
                mTextView.setTextColor(Color.YELLOW);
                break;
            case R.id.font_size_10sp:
                mTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP,10);
                break;
            case R.id.font_size_30sp:
                mTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP,30);
                break;
            case R.id.font_size_50sp:
                mTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP,50);
                break;
            case R.id.font_size_70sp:
                mTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP,70);
                break;
            case R.id.text_hello:
            case R.id.text_menu:
            case R.id.text_MQ:
                mTextView.setText(item.getTitle());
                break;
            case R.id.text_div:
                final EditText editText = new EditText(this);
                AlertDialog dialog = new AlertDialog.Builder(this).setTitle("Please enter the text you want to customize")
                        .setView(editText)
                        .setPositiveButton("Sure".new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                mTextView.setText(editText.getText().toString());
                            }
                        })
                        .setNegativeButton("Cancel".null)
                        .show();
                break;
        }
        return super.onContextItemSelected(item); }}Copy the code

So much for the use of Menu.

Give it a thumbs up before you go!