中心动作栏标题 [英] Center Action bar title

查看:86
本文介绍了中心动作栏标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Android中将活动的操作栏标题居中?

How can I center activity's action bar title in Android?

对于这个特定主题,我已经看到许多关于SO的问题.每个答案都回到使用自定义视图"并拥有自己的工具栏.

I've seen MANY questions on SO for this specific topic. And every answer comes back to "using custom view" and having your own toolbar.

我找到了一种无需创建自定义视图即可使用的解决方案.

I've found a solution that works without creating a custom view.

推荐答案

在您的Activity中具有此方法:

private void centerTitle() {
    ArrayList<View> textViews = new ArrayList<>();

    getWindow().getDecorView().findViewsWithText(textViews, getTitle(), View.FIND_VIEWS_WITH_TEXT);

    if(textViews.size() > 0) {
        AppCompatTextView appCompatTextView = null;
        if(textViews.size() == 1) {
            appCompatTextView = (AppCompatTextView) textViews.get(0);
        } else {
            for(View v : textViews) {
                if(v.getParent() instanceof Toolbar) {
                    appCompatTextView = (AppCompatTextView) v;
                    break;
                }
            }
        }

        if(appCompatTextView != null) {
            ViewGroup.LayoutParams params = appCompatTextView.getLayoutParams();
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            appCompatTextView.setLayoutParams(params);
            appCompatTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
        }
    }
}

然后,只需在您的onCreate()中调用它即可:

Then, just call it in your onCreate():

centerTitle();

就是这样!

这篇关于中心动作栏标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆