1 在资源中创建一个新的menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action button -->
<item
android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:showAsAction="ifRoom"
android:title="@string/action_search"/>
<!-- Settings, should always be in the overflow -->
<item
android:id="@+id/action_settings"
android:showAsAction="never"
android:title="@string/action_settings"/>
</menu>
新的menu即是一个ActionBar,包含2个Item, 第一个是图标icon方式呈现, 第二个是文字, 会缩到overflow里
2 绑定到activity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.main_activity_actions, menu);
return true;
}
3 实现ActionBar响应事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
要点:
1 用资源menu生成
2 Activity可以用MenuInflater完成ActionBar对Activity的填充
3 onOptionsItemSelector是ActionBar的响应事件