趁着快上课,赶紧把今天学习的东西记录一下!!
今天来讲讲Menu这个类!但是听一个大牛说Menu已经不推荐使用了,但是我觉的还是要学习学习!
首先可以通过两种方式来创建自己的Menu,第一种是通过XML文件,第二种是在java代码程序中创建,至于选哪一种,看个人爱好!本人推荐在XML中创建,这样符合MVC模型的要求!
第一种在XML中创建,在res目录下创建一个menu目录
menu.xml
:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/about"
android:title="关于"/>
<item
android:id="@+id/exit"
android:title="退出"/>
</menu>
然后在java代码中重写onCreateOptionsMenu方法,这个方法是系统自动调用!
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();//这个Inflater东东,下次会来讲。
inflater.inflate(R.menu.menu, menu);//设置menu界面为res/menu/menu.xml
return true;
}
第二种在Java程序中创建:
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "OK");
menu.add(0, 1, 1, "NO");
return true;
}
看看menu.add这个方法:
public abstractMenuItemadd (int groupId, int itemId, int order,CharSequence title)
Add a new item to the menu. This item displays the given title for its label.
Parameters
groupId | The group identifier that this item should be part of. This can be used to define groups of items for batch state changes. Normally useNONE if an item should not be in a group. |
---|---|
itemId | Unique item ID. Use NONE if you do not need a unique ID. |
order | The order for the item. Use NONE if you do not care about the order. SeegetOrder() . |
title | The text to display for the item. |
Returns
- The newly added menu item.
接下的事是什么呢?不用猜又是监听器这个角色了!看看一下官方文档,可以找到
Handling click events
When the user selects an item from the options menu (including action items in the action bar),the system calls your activity'sonOptionsItemSelected()
method. This method passes theMenuItem
selected. Youcan identify the item by callinggetItemId()
, which returns the uniqueID for the menu item (defined by theandroid:id
attribute in the menu resource or with aninteger given to theadd()
method). You can matchthis ID against known menu items to perform the appropriate action. For example:
如果用的是XML菜单的话,就像下面来写
public boolean onOptionsItemSelected(MenuItem item) {
int item_id = item.getItemId();
switch (item_id) {
case R.id.about:
Intent intent = new Intent();
intent.setClass(MenuTextActivity.this, MenuDemoActivity.class);
startActivity(intent);
MenuTextActivity.this.finish();
break;
case R.id.exit:
MenuTextActivity.this.finish();
break;
}
return true;
}
如果用java的菜单的话,就用下面来写:
public boolean onOptionsItemSelected(MenuItem item) {
int item_id = item.getItemId();
switch (item_id) {
case 0:
case 1:
Intent intent = new Intent();
intent.setClass(MenuDemoActivity.this, MenuTextActivity.class);
startActivity(intent);
MenuDemoActivity.this.finish();
break;
}
return true;
}
就这么简单,唉!快敲铃上课了,快闪!