The use of menu in Android highlights

Recently, I have been studying the content of the MaterialDesign department, and I have used the content of menu when studying Toolbar and NavigationView. I feel that I don’t understand it very well. It can be said that I don’t know. I can only simply write a menu and nothing else. So to sum up, I hope it helps everyone! ! !

Knowledge points that will be explained in this article

  • Use of menu
  • Attribute description of menu
  • Notes on the use of menu

1. Use of menu

First, let me explain the storage location of the menu. When creating a project, there is no menu folder, so here you have to create a menu folder by yourself, and then create a new menu file. Just look at the picture below for the specific location (because this picture has a corresponding style, the popup that pops up has a background color)!

the location of the menu file

Let's introduce how to write the menu file and the meaning of each attribute

<?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_search"
        android:icon="@drawable/ic_search_black_24dp"
        android:title="搜索"
        app:actionViewClass="android.widget.SearchView"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/menu_cycling"
        android:icon="@mipmap/ic_directions_bike_white_24dp"
        android:title="去知乎的Toolbar"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/menu_other"
        android:title="去网易云音乐的ToolBar"
        app:showAsAction="never" />

    <item
        android:id="@+id/menu_more"
        android:title="更多">
        <menu>
            <item
                android:id="@+id/menu_more1"
                android:title="更多1" />
            <item
                android:id="@+id/menu_more2"
                android:title="更多2" />
            <item
                android:id="@+id/menu_more3"
                android:title="更多3" />
        </menu>
    </item>

</menu>

This is a relatively complex menu file, and there will be no more items below for a general menu. Let's see the effect first!

Display of multi-layer menu files

After seeing the effect, we have a good understanding of the attributes. Here, let's explain the attribute values ​​of the corresponding menu tags:

2. Attribute description of menu

2.1 Attribute description of item

There are a lot of attributes here, but I personally feel that there are many of them that are not useful. The ones listed are some commonly used attributes.

  • android:id ID of the control
  • The icon of the android:icon space (if it is displayed on the Toolbar, the image will be displayed, and in the overflow menu, only the text will be displayed)
  • android:title The title displayed (that is, the content of the entry)
  • app:actionViewClass introduces a View (this is used when implementing search)
  • app:showAsAction display method
    • ifRoom If there is space, it will be displayed on the ToolBar, and when there is insufficient space, it will be displayed in the list
    • always always displayed on the ToolBar (if there is no space, it will still be displayed in the list, in order)
    • collapseActionView (usually used in conjunction with ifRoom) declares that the action view should be collapsed into a button, which expands when the user selects the button. This property is mainly used to implement self-meaning overflow menus. You can set some items in it to implement the overflow menu (the only difference between this custom overflow menu and the default overflow menu is that it can display icons )
    • never will not be displayed on the Toolbar, it will be displayed in the column list
    • withText means that the title of the menu will be displayed if there is enough space in the display. But I tried and didn't see it, please let the god who knows it!
  • android:titleCondensed When the content you set is too long, you can use this attribute for a short description
  • android:onClick is similar to View's onClick method, setting a click event
  • android:checkable Whether the menu can be checked, if it can be checked, set it to true
  • android:checked Whether the menu can be selected, if it can be selected, set to true
  • android:visible menu is displayed
  • android:enabled Whether the menu item is available, if available is true. It is mainly used when customizing the overflow menu, whether the corresponding response can be made.
  • android:orderInCategory menu priority, integer type, the smaller the number, the higher the priority

2.2 Attribute description of group

It is mainly an attribute of a group, similar to the style of RadioGroup, mainly to achieve check! Some of the properties inside are similar to the above, here is mainly one property

  • android:checkableBeharior sets the type of check behavior
    • none is not selectable
    • All items in the all group can be checked (using checkboxes)
    • single only one item can be checked (using radio buttons)

The following is about the use of the group tag

<?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/app_bar_search"
        android:icon="@drawable/ic_search_black_24dp"
        android:title="Search"
        app:actionViewClass="android.widget.SearchView"
        app:showAsAction="always" />
    <item
        android:id="@+id/menu_delete"
        android:icon="@mipmap/ic_delete"
        android:title="删除"
        app:showAsAction="always|collapseActionView">

        <menu>
            <group android:checkableBehavior="all">
                <item android:title="group1" />
                <item android:title="group2" />
                <item android:title="group3" />
            </group>
        </menu>
    </item>
    <item
        android:id="@+id/menu_setting"
        android:icon="@mipmap/ic_delete"
        android:title="设置"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/menu_other"
        android:icon="@mipmap/ic_delete"
        android:title="不知道什么"
        app:showAsAction="ifRoom" />
</menu>

Here is the group displayed through the custom overflow menu, see the following picture for the specific effect

group display

When setting the menu secondary menu (whether it is custom or system), the text color of the previous label is black. I have not found a good solution for this. I hope to know and leave a message! ! ! thanks

3. Notes on using the menu

Here I mainly like to explain some of the problems I encountered in the development of menu

  • How to display menu in Fragment?
  • How will Activity and Fragment use menu at the same time?
  • How do Activity and Fragment handle click events at the same time?
  • How to dynamically change the menu?
  • How to simplify the operation when multiple activities use one menu at the same time?

These problems, in the usual development, I believe many people will not notice! Therefore, it is necessary to share the relevant content with you here.

3.1 How to display menu in Fragment?

The menu file displayed in Fragment is similar to that in Activity, but this code must be added before hanging on View setHasOptionsMenu(true);(basically loading onCreat() above), otherwise it will not be displayed. . .

public class Main1Fragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main1, container, false);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_main_fragment1, menu);
    }
}

The above code is the method of displaying menu in Fragment!

3.2 How will Activity and Fragment use menu at the same time to display?

Is it a strange question, what is your answer? Has it become ambiguous? In fact, some interviewers are very concerned about these details. The answer is superimposed display, what kind of superimposed display? A simple explanation, you add a menu entry of settings in Activity, if you also write one in Fragment, then a menu file of Fragment will be added to the menu.

like this

3.3 How do Activity and Fragment handle click events at the same time?

Some people may ask, how to deal with the click event? In fact, the processing is very simple, that is, onOptionsItemSelectedprocessing the corresponding click event. onOptionsItemSelectedBut there is one point to pay attention to, that is, the return value of the Activity method! This should be returned by default to super.onOptionsItemSelected(item)prevent Fragment from receiving the corresponding click event after the event is processed!

  • Activity onOptionsItemSelectedmethod:
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_setting:
                Log.e(TAG, "onOptionsItemSelected: setting");
                return true;
            case R.id.menu_other:
                Log.e(TAG, "onOptionsItemSelected: other" );
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
  • Fragment's onOptionsItemSelectedmethod:
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.fragment1:
                Log.e(TAG, "onOptionsItemSelected: fragment1" );
                return true;
            case R.id.fragment2:
                Log.e(TAG, "onOptionsItemSelected: fragment2" );
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

In this way, all click events can be responded accordingly.

3.4 How to dynamically change the menu?

Some people may say that the menu is refreshed dynamically but it is unsuccessful. In fact, it is invalidateOptionsMenu();caused by not calling the method to notify the menu to refresh. Let's take a look at the code for menu refresh:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.fragment1:
                Log.e(TAG, "onOptionsItemSelected: fragment1");
                isRefeesh = true;
                getActivity().invalidateOptionsMenu();
                return true;
            case R.id.fragment2:
                Log.e(TAG, "onOptionsItemSelected: fragment2");
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        MenuItem item = menu.findItem(R.id.fragment1);
        if (isRefeesh) {
            item.setTitle("刷新后的fragment1");
        } else {
            item.setTitle(item.getTitle());
        }
    }

Let’s talk about the corresponding logic here . This method invalidateOptionsMenu();will be repeated when it is called onPrepareOptionsMenu. Here I use a flag to mark whether to refresh or not. Why is there this flag? Because onPrepareOptionsMenuit is called when the menu is prepared, it will be called once when it comes in, and it will be called again after clicking.

3.5 How to simplify the operation when multiple activities use one menu at the same time?

This is equivalent to an inheritance relationship. In fact, this problem is also a corresponding superposition problem, as long as you remember that menus can be superimposed. Just load the parent's menu in your onCreateOptionsMenumethod, like below!

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);//调用这一句保证父类的菜单项可以正常加载
    getMenuInflater().inflate(R.menu.menu_main_fragment,menu);//加载子类自己的菜单项
    return true;
}

Basically, this is all about the use of the menu. There may be some inaccuracies in the summary. If you have any questions about the use of the menu, you can leave me a message.

Guess you like

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