例如:
首先創建一個文件夾, /res/menu
並創建一個新/res/menu/的menu.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Submenu 1">
<menu>
<item android:id="@+id/option11"
android:title="1 1" />
<item android:id="@+id/option12"
android:title="1 2" />
<item android:id="@+id/option13"
android:title="1 3" />
</menu>
</item>
<item android:title="Submenu 2">
<menu>
<item android:id="@+id/option21"
android:title="2 1" />
<item android:id="@+id/option22"
android:title="2 2" />
</menu>
</item>
<item android:title="Submenu 3">
<menu>
<item android:id="@+id/option31"
android:title="3 1" />
<item android:id="@+id/option32"
android:title="3 2" />
</menu>
</item>
</menu>
修改主程序, 重寫onCreateOptionsMenu(Menu)和onOptionsItemSelected(MenuItem):
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
String myMenuitem = null;
switch (item.getItemId()){
case (R.id.option11): myMenuitem="option 1 1"; break;
case (R.id.option12): myMenuitem="option 1 2"; break;
case (R.id.option13): myMenuitem="option 1 3"; break;
case (R.id.option21): myMenuitem="option 1 1"; break;
case (R.id.option22): myMenuitem="option 1 2"; break;
case (R.id.option31): myMenuitem="option 1 1"; break;
case (R.id.option32): myMenuitem="option 1 2"; break;
}
Toast.makeText(this, myMenuitem, Toast.LENGTH_LONG).show();
return true;
}
沒有留言:
發佈留言