Android标题居中的Toolbar

这篇博客介绍了如何在Android中让Toolbar的标题居中,避免使用额外的TextView。作者首先分享了通过在Toolbar内添加TextView并设置layout_gravity为center的方法,然后提出通过创建CenterTitleToolbar子类并重写setTitle()方法来简化过程,实现了只改动Toolbar内部代码就能实现标题居中的目标。
摘要由CSDN通过智能技术生成

2017年特意写第一篇博客开个头。之前一直不写博客的原因,一个是懒,另一个是因为觉得自己没那个能力,会误导别人。但是最近特别想听听别人的意见,所以就下定决心开始写博客。废话不说,赶快开波。

前言

用过Toolbar的都知道标题是在左边的,但通常UI都要求我们把标题居中。没用过的童鞋可以看看泡网的一篇文章android:ToolBar详解(手把手教程)。我并不想自己写一个布局来充当Toolbar,因为那样会增加不少工作量。但怎样才能把Toolbar的标题居中?
有问题先google。如果你还在百度的话,我也没什么办法了。谷歌后找到这样一种方法。在原来的Toolbar里面加上一个TextView,标题居中的关键是第12行,将layout_gravity设置成center。

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary">

        <TextView
            android:id="@+id/toolbar_title"
            style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"/>
    </android.support.v7.widget.Toolbar>

接着再来个helper类。很简单的一个类,看看init方法就可以过了。

public class ToolbarHelper {
    private TextView mTitleTextView;
    private Toolbar mToolbar;

    public void init(AppCompatActivity activity, Toolbar toolbar, TextView titleTextView) {
        if (activity == null) {
            return;
        }
        mTitleTextView = titleTextView;
        mToolbar = toolbar;
        activity.setSupportActionBar(toolbar);
        // titleTextView不为null才设置actionbar不显示Title
        if (titleTextView != null) {
            ActionBar actionBar = activity.getSupportActionBar();
            if (actionBar != null) {
                // 不显示title和subTitle
                actionBar.setDisplayShowTitleEnabled(f
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值