菜单
菜单 |
1、布局 <menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/item1"
android:title="功能1">
</item>
<item
android:id="@+id/item2"
android:title="功能2">
</item>
<item
android:id="@+id/item3"
android:title="功能3">
</item>
<item
android:id="@+id/item4"
android:title="功能4">
</item>
<item
android:id="@+id/item5"
android:title="功能5">
</item>
</menu>
|
2、核心代码: package cn.zengfansheng.menu; 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);
return true;
}
/*
* 当菜单项被选择时
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();// 获取当前的菜单id
switch (itemId) {
case R.id.item1:
Toast.makeText(getApplicationContext(), itemId+"被选中了。。。", 0).show();
break;
case R.id.item2:
Toast.makeText(getApplicationContext(), itemId + "被选中了。。。", 0)
.show();
break;
case R.id.item3:
Toast.makeText(getApplicationContext(), itemId + "被选中了。。。", 0)
.show();
break;
case R.id.item4:
Toast.makeText(getApplicationContext(), itemId + "被选中了。。。", 0)
.show();
break;
case R.id.item5:
Toast.makeText(getApplicationContext(), itemId + "被选中了。。。", 0)
.show();
break;
}
return super.onOptionsItemSelected(item);
}
} |
结果: |