创建菜单资源的时候,通过指定android:showAsAction 属性,可以将菜单项在动作栏中显示:
<item
android:id="@+id/change_bg"
android:icon="@drawable/ic_launcher"
android:alphabeticShortcut="g"
android:showAsAction="ifRoom|withText"
android:title="更换背景"/>
对于动作栏子项的初始化和响应与选项菜单的方法相同,都是在Activit 中重写onCreateOptionsMenu() 和onOptionsItemSelected() 方法:
@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) {
// 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();
switch(id){
...
}
return true;
}
在Activity中的onCreate() 方法中,通过调用getActionBar() 方法可以获取ActionBar 实例,然后再调用hide() 或者show() 方法,可以实现动作栏的隐藏或者显示。
ActionBar actionBar = getActionBar();
//show Action Bar
actionBar.show();
//hide Action Bar
actionBar.hide();