设置toolbar标题居中

来源:互联网 发布:php curl 设置头部 编辑:程序博客网 时间:2024/05/19 17:03
废话不多说,直接上代码。然后调用

customizeToolbar(mToolbar);

代入参数即可。亲测有效
public void customizeToolbar(Toolbar toolbar){    // Save current title and subtitle    final CharSequence originalTitle = toolbar.getTitle();    final CharSequence originalSubtitle = toolbar.getSubtitle();    // Temporarily modify title and subtitle to help detecting each    toolbar.setTitle("title");    toolbar.setSubtitle("subtitle");    for(int i = 0; i < toolbar.getChildCount(); i++){        View view = toolbar.getChildAt(i);        if(view instanceof TextView){            TextView textView = (TextView) view;            if(textView.getText().equals("title")){                // Customize title's TextView                Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);                params.gravity = Gravity.CENTER_HORIZONTAL;                textView.setLayoutParams(params);                           } else if(textView.getText().equals("subtitle")){                // Customize subtitle's TextView                Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);                params.gravity = Gravity.CENTER_HORIZONTAL;                textView.setLayoutParams(params);                            }        }        // Restore title and subtitle        toolbar.setTitle(originalTitle);        toolbar.setSubtitle(originalSubtitle);    }}

0 0