码迷,mamicode.com
首页 > 其他好文 > 详细

ActionBar的使用

时间:2014-10-09 18:43:37      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   http   color   io   使用   ar   文件   

ActionBar的使用很普遍,可以充当工具栏使用。本文介绍如何使用ActionBar。

1.ActionBar一般包含有多个工具按钮。所以,需要新建一个xml文件来存放ActionBar中的内容。在程序的res文件夹下新建一个menu文件夹,在menu中新建一个xml命名为optionmenu。

bubuko.com,布布扣

注:要在menu的元素下创建,这样在xml中可以直接生成menu代码。

2.在optionmenu.xml中加入actionbar内容的布局。因为本文的actionbar中的item使用了图片背景,所以在res下新建一个drawable文件夹用来存放背景图片,图片可以在下面这个网站下载http://www.easyicon.net/(个人认为,这个网址还是很方便的)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:id="@+id/zoomin"
        android:icon="@drawable/zoomin"
        android:title="放大"
        android:showAsAction="always"/>
    <item 
        android:id="@+id/zoomout"
        android:icon="@drawable/zoomout"
        android:title="缩小"
        android:showAsAction="always"/>
    <item 
        android:id="@+id/mapscreen"
        android:icon="@drawable/map"
        android:title="全图"
        android:showAsAction="always"/>
    <item 
        android:id="@+id/clear"
        android:icon="@drawable/clear"
        android:title="清除"
        android:showAsAction="always"/>
    
</menu>

3.布局完成后,就要在activity中设置该actionbar的显示。在onCreate函数中加入代码:

ActionBar actionBar = this.getActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP, ActionBar.DISPLAY_HOME_AS_UP);

4.这只是定义了ActionBar,下一步需要找到刚开始定义的xml文件。这需要重写onOptionsItemSelected函数。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.optionmenu, menu);
    //SearchView searchView = (SearchView) menu.findItem(R.id.actionview).getActionView();
    return true;
 }

5.到这一步就可以显示了:

bubuko.com,布布扣

6.点击事件

 1 @Override
 2     public boolean onOptionsItemSelected(MenuItem item){
 3         switch (item.getItemId()) {
 4         case android.R.id.home:
 5             Toast.makeText(this, "单击了图标", Toast.LENGTH_SHORT).show();
 6             return true;
 7         case R.id.zoomin:
 8             Toast.makeText(this, "放大", Toast.LENGTH_SHORT).show();
 9             return true;
10         case R.id.zoomout:
11             Toast.makeText(this, "缩小", Toast.LENGTH_SHORT).show();
12             return true;
13         case R.id.mapscreen:
14             Toast.makeText(this, "全图", Toast.LENGTH_SHORT).show();
15             return true;
16         case R.id.clear:
17             Toast.makeText(this, "清除", Toast.LENGTH_SHORT).show();
18             return true;25         default:
26             return super.onOptionsItemSelected(item);
27         }
28     }

bubuko.com,布布扣

另外,可以更换项目的标题图片:在AndroidManifest.xml中修改<application>标签中的android:icon的值就ok了。

ActionBar的使用

标签:android   style   blog   http   color   io   使用   ar   文件   

原文地址:http://www.cnblogs.com/skdpengkai/p/4013649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!