android控件之menu(一)

MytestActivity.java

package com.android.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MytestActivity extends Activity {
	public TextView myTextView;
	public static final int NUM1 = Menu.FIRST;  
    public static final int NUM2 = Menu.FIRST+1;  
    public static final int NUM3 = Menu.FIRST+2; 
    public static final int NUM4 = Menu.FIRST+3;  
    public static final int NUM5 = Menu.FIRST+4;  
    public static final int NUM6 = Menu.FIRST+5; 
    public static final int NUM7 = Menu.FIRST+6; 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        myTextView = (TextView)findViewById(R.id.myTextView);
        
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, NUM1, 1, "选项1").setIcon(android.R.drawable.star_big_off);
		menu.add(0, NUM2, 2, "选项2").setIcon(android.R.drawable.star_big_on);
		menu.add(0, NUM3, 3, "选项3").setIcon(android.R.drawable.ic_menu_add);
		menu.add(0, NUM4, 4, "选项4").setIcon(android.R.drawable.ic_menu_camera);
		menu.add(0, NUM5, 5, "选项5");
		menu.add(0, NUM6, 6, "选项6");
		menu.add(0, NUM7, 7, "选项7");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		switch(item.getItemId()){
		case NUM1:
			myTextView.setText("选项1");
			break;
		case NUM2:
			myTextView.setText("选项2");
			break;
		case NUM3:
			myTextView.setText("选项3");
			break;
		case NUM4:
			myTextView.setText("选项4");
			break;
		case NUM5:
			myTextView.setText("选项5");
			break;
		case NUM6:
			myTextView.setText("选项6");
			break;
		case NUM7:
			myTextView.setText("选项7");
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public void onOptionsMenuClosed(Menu menu) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "选项菜单关闭了", Toast.LENGTH_SHORT).show();
		super.onOptionsMenuClosed(menu);
	}
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "选项菜单显示之前onPrepareOptionsMenu方法会被调用,你可以用此方法来根据打当时的情况调整菜单", Toast.LENGTH_SHORT).show();
		return super.onPrepareOptionsMenu(menu);
	}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/myTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>

结果如图

android控件之menu(一)_第1张图片


你可能感兴趣的:(android控件之menu(一))