ToolBar 常用属性

默认的ToolBar可能是这个样子

这里写图片描述

有时候可能需要标题居中,可在布局中添加一个TextView

 <android.support.v7.widget.Toolbar
        android:id="@+id/toolBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        app:titleTextColor="@android:color/white">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_gravity="center"
            android:text="Center Title"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@android:color/white"
            android:textStyle="bold"/>
    </android.support.v7.widget.Toolbar>

然后去掉默认的Title

  Toolbar toolbar = ((Toolbar) findViewById(R.id.toolBar));
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("");

然后界面应该是这个样子

这里写图片描述

二级页面看起来应该差一个返回按钮,这也很简单

  getSupportActionBar().setDisplayHomeAsUpEnabled(true);

返回按钮的颜色可能不是你想要的

在style 中新加一个style 如下

 <style name="toolBar">
        <item name="colorControlNormal">@android:color/white</item>
    </style>

然后在ToolBar布局中添加属性

 app:theme="@style/toolBar"

这个时候ToolBar应该长这个样子了

这里写图片描述


右边再来一个按钮

menu下新建一个menu文件

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context=".MainActivity">
    <item
        android:id="@+id/ab_search"
        android:icon="@drawable/menu_0"
        android:title="action_search"
        app:showAsAction="ifRoom"/>
</menu>

Activity中onCreateOptionsMenu

  public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.toolbar_main_menu, menu);
        return true;
    }

再加上事件监听

  @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        toast("onOptionsItemSelected");
        return super.onOptionsItemSelected(item);
    }

这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值