Menu菜单

Menu菜单:
在menu目录下新建main_menu.xml:

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

    <item android:id="@+id/menu1"
        android:title="菜单1"
        android:icon="@mipmap/ic_launcher"/>

    <item android:id="@+id/menu2"
        android:title="菜单2"
        android:icon="@mipmap/ic_launcher"/>

    <item android:id="@+id/menu3"
        android:title="菜单3"
        android:icon="@mipmap/ic_launcher"/>

    <item android:id="@+id/menu4"
        android:title="菜单4"
        android:icon="@mipmap/ic_launcher"/>

</menu>

举例新建了四个菜单
MainActivity:

package com.fitsoft;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        new MenuInflater(this).inflate(R.menu.main_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
            case R.id.menu1:Toast.makeText(this,"用户点击了菜单1",Toast.LENGTH_SHORT).show();break;
            case R.id.menu2:Toast.makeText(this,"用户点击了菜单2",Toast.LENGTH_SHORT).show();break;
            case R.id.menu3:Toast.makeText(this,"用户点击了菜单3",Toast.LENGTH_SHORT).show();break;
            case R.id.menu4:Toast.makeText(this,"用户点击了菜单4",Toast.LENGTH_SHORT).show();break;
            default:break;
        }

//        if(item.getTitle().equals("菜单1")){
//            Toast.makeText(this,"用户点击了菜单1",Toast.LENGTH_SHORT).show();
//        }else if(item.getTitle().equals("菜单2")){
//            Toast.makeText(this,"用户点击了菜单2",Toast.LENGTH_SHORT).show();
//        }else if(item.getTitle().equals("菜单3")){
//            Toast.makeText(this,"用户点击了菜单3",Toast.LENGTH_SHORT).show();
//        }else if(item.getTitle().equals("菜单4")){
//            Toast.makeText(this,"用户点击了菜单4",Toast.LENGTH_SHORT).show();
//        }

        return super.onOptionsItemSelected(item);
    }
}

在onCreateOptionsMenu方法中将布局加入菜单,并返回true,在onOptionsItemSelected方法中设置菜单的点击事件。
效果图:

posted @ 2019-09-16 20:08  干翻苍穹  阅读(365)  评论(0编辑  收藏  举报