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布局文件:






你可能感兴趣的:(android开发)