Use an instance of Menu in an activity

Why use Menu?

When a lot of menus need to be displayed on the mobile interface, the screen will be covered with menus. At this time, menus can be used to display the menus without occupying any screen space.

Let's take a look at the effect first:

Implementation steps:

1. Create a folder menu in the res directory, res—new—Directory, enter menu, and then create a new menu file called main, menu——new—Menu resource file, and then add the following code to main
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

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

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

</menu>

2. Rewrite the onCreateOptionMenu() method and the onOptionsItemSelected() method in the activity, and you're done

public class FirstActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layout);
    }
     //给当前活动创建菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //参数一:指定通过哪个资源文件来创建菜单,parems2:创建的菜单放大哪个Menu对象中
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
        //创建相应事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_item:
                Toast.makeText(FirstActivity.this,"You clicked  Add",Toast.LENGTH_SHORT).show();
                break;
            case R.id.remove_item:
                Toast.makeText(FirstActivity.this,"You clicked Remove",Toast.LENGTH_SHORT).show();
                break;
            default:
        }
        return true;
    }
}

Guess you like

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