当我们新建应用的打开的时候,标题栏右边默认都有三个小点,如下图,知道它是干嘛的吗,下面容我慢慢道来
点击的时候会默认弹出setting选项,这个就是我们要用的menu菜单了。
menu菜单的定义就在res文件夹下的menu文件夹中。我这里的文件名叫main.xml
下面我多加一项:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.hello.MainActivity" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never"/>
<item
android:id="@+id/action_settings2"
android:orderInCategory="100"
android:title="@string/action_settings2"
app:showAsAction="never"/>
</menu>
string.xml中内容:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Hello</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">文学</string>
<string name="action_settings2">地理</string>
</resources>
这个main.xml文件使用就在activity的 onCreateOptionsMenu 方法中,注意这里要return true才可以看到菜单,如果return false,上面的三个小点的菜单是看不见的,当然也使用不了
@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;
}
main.xml中的条目项在哪里控制呢,activity有个方法叫做 onOptionsItemSelected,这个方法可以监听条目的点击事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Toast.makeText(getApplicationContext(), "文学", Toast.LENGTH_SHORT).show();
return true;
}else if(id == R.id.action_settings2){
Toast.makeText(getApplicationContext(), "地理", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
我这里只弹一个吐丝,下面是点击的效果图