Android 创建菜单栏

Android 创建菜单栏(用Java实现方法)

java代码如下:

package com.example.Menudemo;

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

public class MainActivity extends Activity {

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

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// // Inflate the menu; this adds items to the action bar if it is
		// present.
		// getMenuInflater().inflate(R.menu.main, menu);
		menu.add(1, 1001, 0, "菜单1");
		menu.add(1, 1002, 0, "菜单2");
		menu.add(1, 1003, 0, "菜单3");
		menu.add(1, 1004, 0, "菜单4");
		menu.add(1, 1005, 0, "菜单5");
		menu.add(1, 1006, 0, "菜单6");
		menu.add(1, 1007, 0, "菜单7");
		

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// // Handle action bar item clicks here. The action bar will
		// // automatically handle clicks on the Home/Up button, so long
		// // as you specify a parent activity in AndroidManifest.xml.
		// int id = item.getItemId();
		// if (id == R.id.action_settings) {
		// return true;
		// }
		int id = item.getItemId();
		switch (id) {
		case 1001:
			Toast.makeText(getApplicationContext(), "这是菜单1", Toast.LENGTH_SHORT).show();
			break;
		case 1002:
			
			Toast.makeText(getApplicationContext(), "这是菜单2", Toast.LENGTH_SHORT).show();
			
			break;
		case 1003:
			Toast.makeText(getApplicationContext(), "这是菜单3", Toast.LENGTH_SHORT).show();
			break;
		case 1004:
			Toast.makeText(getApplicationContext(), "这是菜单4", Toast.LENGTH_SHORT).show();
			break;
		case 1005:
			Toast.makeText(getApplicationContext(), "这是菜单5", Toast.LENGTH_SHORT).show();
			break;
		case 1006:
			Toast.makeText(getApplicationContext(), "这是菜单6", Toast.LENGTH_SHORT).show();
			break;
		case 1007:
			Toast.makeText(getApplicationContext(), "这是菜单7", Toast.LENGTH_SHORT).show();
			break;

		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}
}


运行结果如下:




你可能感兴趣的:(android)