Toolbar的高级使用

Toolbar的高级使用

随着android studio的盛行,eclipse退出历史舞台,material design已日渐流行,本文简单介绍一下toolbar的基本使用方法

下面是本人封装后的toolbar代码块
此处本人使用自定义的title,setDisplayShowTitleEnabledfalse

private void initToolbar() {
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar == null)
        return;
    title = (AppCompatTextView) findViewById(R.id.title)
    //setup width of custom title to match in parent toolbar
    toolbar.postDelayed(new Runnable() {
        @Override
        public void run() {
            int maxWidth = toolbar.getWidth();
            int titleWidth = title.getWidth();
            int iconWidth = maxWidth - titleWidth;

            if (iconWidth > 0) {
                //icons (drawer, menu) are on left and right side
                int width = maxWidth - titleWidth * 2;
                title.setMinimumWidth(width);
                title.getLayoutParams().width = width;
            }
        }
    }, 0);
    toolbar.setTitle(null);
    setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowHomeEnabled(true);    getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false);
    setNavigationIconColor(Color.WHITE, toolbar);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });
    initColor();
}

initColor是一个恢复toolbar背景颜色的代码,主要用于在toolbar背景色透明度变化的界面下回到其他界面用于恢复

private void initColor() {
if (toolbar != null) {
ColorDrawable background = (ColorDrawable) toolbar.getBackground();
background.setAlpha(255);
}
}
这段代码看懂了,也知道怎么动态改变toolbar的背景色了吧

上文中AppCompatTextView需要在 compile 'com.android.support:appcompat-v7:22.1.1' 即google自家库appcompat-v722.0.0以上版本,此版本下ActionBarActivity 已过时,使用AppCompatActivity替代可以很好的兼容使用Toolbar

最后贴出本人使用的toolbar布局文件:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
style="@style/ToolBarStyle"  xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/green"
android:minHeight="?attr/actionBarSize"
>

<android.support.v7.widget.AppCompatTextView
    android:id="@+id/title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:text="@string/app_name"
    android:textColor="@color/white"
    android:textSize="@dimen/text_navigation"/>
</android.support.v7.widget.Toolbar>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值