如何写菜单

Mainactivity

package com.example.menuDemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Toast;

public class MainActivity extends Activity {

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

    // 这个方法给menu文件打气为菜单界面
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    // 当menu菜单打开时的操作
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        Toast.makeText(getApplicationContext(), "菜单要打开了", 0).show();
        return super.onMenuOpened(featureId, menu);
    }

    // 当点击某个菜单时,要做的操作
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings1) {
            Toast.makeText(getApplicationContext(), "你点击了菜单一", 0).show();
            return true;
        }
        if (id == R.id.action_settings2) {
            Toast.makeText(getApplicationContext(), "你点击了菜单二", 0).show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

// 当选项菜单关闭时调用的方法
    @Override
    public void onOptionsMenuClosed(Menu menu) {
        Toast.makeText(getApplicationContext(), "菜单要关闭了", 0).show();
        super.onOptionsMenuClosed(menu);
    }
}

布局

activity_main

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.menuDemo.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout> 

main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context="com.example.menuDemo.MainActivity" >

    <item  android:id="@+id/action_settings1" android:orderInCategory="100" android:showAsAction="never" android:title="菜单一"/>
    <item  android:id="@+id/action_settings2" android:orderInCategory="100" android:showAsAction="never" android:title="菜单二"/>

</menu>

你可能感兴趣的:(菜单,menu)