废话不多说,直接上代码。然后调用
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);
}
}