您的位置:首页 > 移动开发 > Android开发

Android开发之Android Material Design Toolbar自定义随笔

2015-11-18 17:01 573 查看
一、自定义Toolbar的menu:

在menu下新建menu.xml文件,自定义menu的样式:

1 <menu xmlns:android="http://schemas.android.com/apk/res/android"
2     xmlns:app="http://schemas.android.com/apk/res-auto"
3     xmlns:tools="http://schemas.android.com/tools"
4     tools:context=".MainActivity">
5     <item
6         android:id="@+id/action_search"
7         android:orderInCategory="80"
8         android:title="action_search"
9         app:showAsAction="ifRoom"
10         android:icon="@drawable/search_ic_selector"/>
11 </menu>


二、自定义Toolbar,Toolbar一般是共用:

新建common_toolbar.xml文件:

1 <?xml version="1.0" encoding="utf-8"?>
2 <android.support.v7.widget.Toolbar
3     xmlns:android="http://schemas.android.com/apk/res/android"
4     xmlns:app="http://schemas.android.com/apk/res-auto"
5     android:id="@+id/common_toolbar_top"
6     android:layout_width="match_parent"
7     android:layout_height="wrap_content"
8     android:background="@color/colorPrimary"
9     android:minHeight="?attr/actionBarSize"
10     app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
11     app:navigationIcon="?attr/homeAsUpIndicator"
12     app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
13    >
14 </android.support.v7.widget.Toolbar>


注:其中app:navigationIcon="?attr/homeAsUpIndicator"用于设置返回图标

三、在布局文件中引入自定义的Toolbar:

<include
layout="@layout/common_toolbar">
</include>


四、activity中声明Toolbar以及对menu的事件监听:

注:Activity必须继承AppCompatActivity

1、声明Toolbar:

1 Toolbar toolbar = (Toolbar) findViewById(R.id.common_toolbar_top);
2 setSupportActionBar(toolbar);


2、Toolbar设置标题等:

setTitle(R.string.fragment_for_why_title);


3、对menu进行声明和事件监听:

menu声明:

@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) {
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {

return true;
}

return super.onOptionsItemSelected(item);
}


五、最终效果图:





Demo下载地址:http://shouji.baidu.com/software/item?docid=8118536&from=as
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: