ActionBar使用要点

来源:互联网 发布:淘宝付款后店铺不存在 编辑:程序博客网 时间:2024/05/29 03:24

ActionBar是用于实现各种效果及快捷操作的动作栏,通常位于顶部状态栏的下方。 
其演示效果如下所示: 
图1图2图3


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

  1. Icon和Title
  2. Action Items
  3. Action Overflow

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


ActionBar的整体添加:

  • 在建立Android工程时,在Theme中选择”Holo Light with Dark Action Bar”;
  • 在建立好工程后的res/styles.xml的style标签中的parent属性中设定”android:Theme.Holo”或其子Theme。

ActionBar的整体移除:

  1. 在建立工程时,在Theme中选择”None”;
  2. 在建立好的工程后的res/styles.xml的style标签中的parent属性中设定内容为”android:Theme.Holo.NoActionBar”;
  3. 在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添加点击事件

  1. 重写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);    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  1. 重写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);    }
0 0
原创粉丝点击