public class MenuActivity extends Activity {
private static final int ITEM0 = Menu.FIRST;
private static final int ITEM1 = Menu.FIRST+1;
private Button button1 = null;
private Button button2 = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
button1 = (Button)this.findViewById(R.id.button1);
button2 = (Button)this.findViewById(R.id.button2);
/*设置第2个button不可见*/
button1.setVisibility(View.INVISIBLE);
button2.setVisibility(View.INVISIBLE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu);
menu.add(0, ITEM0, 0, "显示button1");
menu.add(0, ITEM1, 0, "显示button2");
menu.findItem(ITEM1);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case ITEM0:
actionClickMenuItem1();
break;
case ITEM1:
actionClickMenuItem2();
break;
}
return super.onOptionsItemSelected(item);
}
private void actionClickMenuItem2() {
// TODO Auto-generated method stub
setTitle("button2可见");
button2.setVisibility(View.VISIBLE);
button1.setVisibility(View.INVISIBLE);
}
private void actionClickMenuItem1() {
// TODO Auto-generated method stub
setTitle("button1可见");
button1.setVisibility(View.VISIBLE);
button2.setVisibility(View.INVISIBLE);
}
}
<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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button1"
/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button2"
/>
</LinearLayout>