【www.bbyears.com--php应用】
不像actionbar那么固定,Toolbar更像是一般的View元素,可以被放置在view树体系的任意位置,可以应用动画,可以跟着scrollView滚动,可以与布局中的其他view交互。当然,你还可以用Toolbar替换掉actionbar,只需调用 Activity.setActionBar()。
虽然toolbar已经出来很长时间,但还是有些必要再进行简单介绍,
先上布局
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:theme="@style/AppTheme.AppBarOverlay"
>
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerInParent="true"
android:layout_marginLeft="15dp"
android:background="@mipmap/icon_index_search" />
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="搜索"
android:textColor="#956C28"
android:textSize="16sp" />
屏幕快照 2016-04-22 16.38.12
上面的布局呈现的是这种效果,可以在里面进行自定义,也可以通过menu进行控件的编写,如果需要在滑动的时候隐藏toolbar就需要在外面包裹一层APPBarLayout
android:orderInCategory="0"
android:title="定位"
android:icon="@mipmap/icon_index_location"
app:showAsAction="ifRoom" />
在这里可以指定toolbar显示哪些控件,app:showAsAction的属性可以指定该图标是显示在toolbar上还是显示在菜单里,大家可以自行测试,
下面进入核心代码部分,
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.mipmap.icon_index_menu);
setSupportActionBar(toolbar);
可以通过toolbar对象来设置我们需要的结果,例如icon,标题,副标题等等,
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_location) {
return true;
}
return super.onOptionsItemSelected(item);
}
重写上述两个方法进行toolbar上的菜单按钮加载,然后设置监听,到此就结束了。下面说一下需要注意的地方,在布局文件中也可以设置icon、title等,但是需要加入自定义属性的命名空间
xmlns:toolbar="http://schemas.android.com/apk/res-auto"
然后通过toolbar:title=””来设置各种属性。