大家都知道,任務程式離不開菜單,菜單無處不在,哪我們一定要學好ANDROID中的菜單,它給我帶來了不少的功能。相信大家都知道的。好,現在我們開始吧,下面的代碼很簡單。看圖:
<a href="http://blog.51cto.com/attachment/201103/201614140.jpg" target="_blank"></a>
package com.smart;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class SmartMenu extends Activity {
public static final int ITEM0=Menu.FIRST;//系統值
public static final int ITEM1=Menu.FIRST+1;
public static final int ITEM2=Menu.FIRST+2;
public static final int ITEM3=Menu.FIRST+3;
Button button1;
Button button2;
Button button3;
Button button4;
// private Menu menu;
// private Menu menu
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
button3=(Button)findViewById(R.id.button3);
button4=(Button)findViewById(R.id.button4);
button1.setVisibility(View.INVISIBLE);
button2.setVisibility(View.INVISIBLE);
button3.setVisibility(View.INVISIBLE);
button4.setVisibility(View.INVISIBLE);
//
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, ITEM0, 0,"顯示button1");
menu.add(0, ITEM1,0,"顯示button2");
menu.add(0, ITEM2,0,"建立");
menu.add(0, ITEM3,0,"打開");
menu.findItem(ITEM1);//可以設定按鈕的背景
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ITEM0:
actionClickMenuItem1();
break;
case ITEM1:
actionClickMenuItem2();
case ITEM2:
actionClickMenuItem3();
case ITEM3:
actionClickMenuItem4();
}
return super.onOptionsItemSelected(item);
//第一個事件的方法
private void actionClickMenuItem1(){
setTitle("button1可見");
button1.setVisibility(View.VISIBLE);//可見
button2.setVisibility(View.INVISIBLE);//不可見
}
//第2個事件的方法
private void actionClickMenuItem2(){
setTitle("button2可見");
button1.setVisibility(View.INVISIBLE);//不可見
button2.setVisibility(View.VISIBLE);//可見
private void actionClickMenuItem3(){
button3.setVisibility(View.VISIBLE);//可見
button4.setVisibility(View.INVISIBLE);//不可見
private void actionClickMenuItem4(){
button3.setVisibility(View.INVISIBLE);//不可見
button4.setVisibility(View.VISIBLE);//可見
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="我的菜單我做主_1"
/>
<Button
android:id="@+id/button2"
android:text="我的菜單我做主_2"
<Button
android:id="@+id/button3"
android:text="小子,給記住這代碼"
android:id="@+id/button4"
android:layout_width="fill_parent"
android:text="哈哈,你欺負我呀,我就能記住"
</LinearLayout>
本文轉自 llb988 51CTO部落格,原文連結:http://blog.51cto.com/llb988/525525,如需轉載請自行聯系原作者