您的位置:首页 > 其它

ActionBar使用要点

2016-01-18 07:57 691 查看
ActionBar是用于实现各种效果及快捷操作的动作栏,通常位于顶部状态栏的下方。

其演示效果如下所示:







可以看出,ActionBar主要包含以下3部分:

Icon和Title

Action Items

Action Overflow

设置、添加、移除ActionBar的内容

ActionBar的整体添加:

在建立Android工程时,在Theme中选择”Holo Light with Dark Action Bar”;

在建立好工程后的res/styles.xml的style标签中的parent属性中设定”android:Theme.Holo”或其子Theme。

ActionBar的整体移除:

在建立工程时,在Theme中选择”None”;

在建立好的工程后的res/styles.xml的style标签中的parent属性中设定内容为”android:Theme.Holo.NoActionBar”;

在onCreate方法中添加代码

ActionBar actionBar = getActionBar();  actionBar.hide();


设置Icon和Title

修改Icon:

在AndroidManiFest.xml中的activity标签中设置android:logo属性。

修改Title:

在AndroidManiFest.xml中的activity标签中设置android:label属性。

设置Action Items 和Action Overflow

应把所有的Action Items和Action Overflow设置在一个menu资源文件夹中(新建的xml文件以menu为根元素),每个item标签对应一个Action Items或Action Overflow,item标签有如下常用属性:

android:icon——设置Action Items或Action Overflow的图标;

android:title——设置Action Items或Action Overflow的标题;

android:showAsAction

-always——永远显示在Action Items中;

-ifRoom——若Action Bar空间足够,则显示在Action Items上,否则显示在Action Overflow中;

-never——只显示在Action Overflow中。

为Action Items 和Action Overflow添加点击事件

重写onCreateOptionMenu方法,加载menu布局文件:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater _inflater = getMenuInflater();
_inflater.inflate(R.menu.menu_items, menu);
return super.onCreateOptionsMenu(menu);
}


重写onMenuItemSelected方法,为item项添加点击事件:

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {

case R.id.ok:
Toast.makeText(this, "choose ok", Toast.LENGTH_SHORT).show();
break;
case R.id.delete:
Toast.makeText(this, "choose delete", Toast.LENGTH_SHORT).show();
break;
case R.id.email:
Toast.makeText(this, "choose email", Toast.LENGTH_SHORT).show();

default:
break;
}
return super.onMenuItemSelected(featureId, item);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ActionBar Overflow