setSupporrtActionBar与toolbar.setTitle的冲突问题解释

最近在android开发过程中遇到了一个小的问题,就是ToolBar的setTitle方法和setSupportActionBar方法之间会有冲突的问题,问题如下:
如果在setSupportActionBar之后设置setTitle,则后者没有任何效果,如下图所示

如果在之前设置setTitle,则Title可以顺利显示。
本着究其根本的缘故,遂深入源码查询原因。

setSupportActionBar和getSupportActionBar是设置ActionBar的主要方法,是AppCompatActivity的public 方法之一。其主要用来设置ToolBar,至于ToolBar的知识就更多了,在此不多赘述。
我们来看API文档:

QQ图片20170824110952.png

来源:Android Developers

从 Android 3.0(API 级别 11)开始,所有使用默认主题的 Activity 均使用 [ActionBar](https://developer.android.com/reference/android/app/ActionBar.html)
 作为应用栏。不过,经过不同 Android 版本的演化,应用栏功能已逐渐添加到原生 [ActionBar](https://developer.android.com/reference/android/app/ActionBar.html)
 中。因此,原生 [ActionBar](https://developer.android.com/reference/android/app/ActionBar.html)
 的行为会随设备使用的 Android 系统的版本而发生变化。相比之下,最新功能已添加到支持库版本的 [Toolbar](https://developer.android.com/reference/android/support/v7/widget/Toolbar.html)
 中,并且这些功能可以在任何能够使用该支持库的设备上使用。
因此,您应使用支持库的 [Toolbar](https://developer.android.com/reference/android/support/v7/widget/Toolbar.html)
 类来实现 Activity 的应用栏。使用支持库的工具栏有助于确保您的应用在最大范围的设备上保持一致的行为。例如,[Toolbar](https://developer.android.com/reference/android/support/v7/widget/Toolbar.html)
 小部件能够在运行 Android 2.1(API 级别 7)或更高版本的设备上提供 [Material Design](https://developer.android.com/design/material/index.html) 体验,但除非设备运行的是 Android 5.0(API 级别 21)或更高版本,否则原生操作栏不会支持 Material Design.
在 Activity 的 [onCreate()](https://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle))
 方法中,调用 Activity 的 [setSupportActionBar()](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html#setSupportActionBar(android.support.v7.widget.Toolbar))
 方法,然后传递 Activity 的工具栏。该方法会将工具栏设置为 Activity 的应用栏。例如:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);
    }

您的应用现在具有一个基本操作栏。默认情况下,操作栏只包含应用的名称和一个溢出菜单。选项菜单最初只包含 **Settings** 菜单项。您可以按照[添加和处理操作](https://developer.android.com/training/appbar/actions.html)中所述向操作栏和溢出菜单添加更多操作

默认情况下,操作栏只包含应用的名称和一个溢出菜单。
这里有个小坑,就是默认情况下,ToolBar上的应用名是会显示的,如果没有对ToolBar设置setTitle,则默认使用应用名。并且如果在setSupportActionBar之后设置setTitle,则设置无效,仍然显示应用名。

那么,这还是没有解决问题,我们从源码来看(附:最机智的源码查看方式,就是加个断点,然后调试采用force Step):

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.acticity_answer_collection);

    mToolBar.setTitle("");
    setSupportActionBar(mToolBar);
    mToolBar.setNavigationIcon(R.drawable.ic_menu);
    mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        Toast.makeText(AnswerCollectionActivity.this, "menu", Toast.LENGTH_SHORT).show();
      }
    });
    initViewPage();
  }

先看setTitle的代码:

    /**
     * Set the title of this toolbar.
     *
     * <p>A title should be used as the anchor for a section of content. It should
     * describe or name the content being viewed.</p>
     *
     * @param title Title to set
     */
    public void setTitle(CharSequence title) {
        if (!TextUtils.isEmpty(title)) {
            if (mTitleTextView == null) {
                final Context context = getContext();
                mTitleTextView = new AppCompatTextView(context);
                mTitleTextView.setSingleLine();
                mTitleTextView.setEllipsize(TextUtils.TruncateAt.END);
                if (mTitleTextAppearance != 0) {
                    mTitleTextView.setTextAppearance(context, mTitleTextAppearance);
                }
                if (mTitleTextColor != 0) {
                    mTitleTextView.setTextColor(mTitleTextColor);
                }
            }
            if (!isChildOrHidden(mTitleTextView)) {
                addSystemView(mTitleTextView, true);
            }
        } else if (mTitleTextView != null && isChildOrHidden(mTitleTextView)) {
            removeView(mTitleTextView);
            mHiddenViews.remove(mTitleTextView);
        }
        if (mTitleTextView != null) {
            mTitleTextView.setText(title);
        }
        mTitleText = title;
    }

如果setTitle在setSupportActionBar之前就设置了Title,则运行到setSupportActionBar(mToolBar);这里,由于判空函数返回true,则自动跳过这段程序,即setSupportActionBar不执行设置Title,此为正确设置Title状态。
而如果setSupportActionBar在setTitle之前,则把Title默认设置为应用名。

此时进入setTilte方法,由于mTitleTextView不为空,程序运行到最后,mTitleText = title;,即setTitle正确设置了Title,但是为什么没有显示新的Title,仍然显示默认的应用名呢?

这是本文的重点部分。

(1)setSupportActionBar在setTitle之前,把Title默认设置为应用名
setSupportActionBar:

 * @param toolbar Toolbar to set as the Activity's action bar, or {@code null} to clear it
     */
    public void setSupportActionBar(@Nullable Toolbar toolbar) {
        getDelegate().setSupportActionBar(toolbar);
    }
    @Override
    public void setSupportActionBar(Toolbar toolbar) {
        if (!(mOriginalWindowCallback instanceof Activity)) {
            // Only Activities support custom Action Bars
            return;
        }

        final ActionBar ab = getSupportActionBar();
        if (ab instanceof WindowDecorActionBar) {
            throw new IllegalStateException("This Activity already has an action bar supplied " +
                    "by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set " +
                    "windowActionBar to false in your theme to use a Toolbar instead.");
        }

        // If we reach here then we're setting a new action bar
        // First clear out the MenuInflater to make sure that it is valid for the new Action Bar
        mMenuInflater = null;

        // If we have an action bar currently, destroy it
        if (ab != null) {
            ab.onDestroy();
        }

        if (toolbar != null) {
            final ToolbarActionBar tbab = new ToolbarActionBar(toolbar,
                    ((Activity) mOriginalWindowCallback).getTitle(), mAppCompatWindowCallback);
            mActionBar = tbab;
            mWindow.setCallback(tbab.getWrappedWindowCallback());
        } else {
            mActionBar = null;
            // Re-set the original window callback since we may have already set a Toolbar wrapper
            mWindow.setCallback(mAppCompatWindowCallback);
        }

        invalidateOptionsMenu();
    }

通过调试发现,在上述代码中

final ToolbarActionBar tbab = new ToolbarActionBar(toolbar,
                    ((Activity) mOriginalWindowCallback).getTitle(), mAppCompatWindowCallback);

设置了Title为默认的应用名。点进去看看代码如下;

    public ToolbarActionBar(Toolbar toolbar, CharSequence title, Window.Callback callback) {
        mDecorToolbar = new ToolbarWidgetWrapper(toolbar, false);
        mWindowCallback = new ToolbarCallbackWrapper(callback);
        mDecorToolbar.setWindowCallback(mWindowCallback);
        toolbar.setOnMenuItemClickListener(mMenuClicker);
        mDecorToolbar.setWindowTitle(title);
    }
    final CharSequence getTitle() {
        // If the original window callback is an Activity, we'll use it's title
        if (mOriginalWindowCallback instanceof Activity) {
            return ((Activity) mOriginalWindowCallback).getTitle();
        }
        // Else, we'll return the title we have recorded ourselves
        return mTitle;
    }

这里可以发现,如果返回的是个Activity,则使用它的标题,即是默认的应用名,这个在设置Menu菜单的时候可以发现。

8.png

如上图,在左上角的标题即是默认的应用名。

(2)之后通过setTitle设置Title,为什么没有反应呢?

调试程序跳转到setTitle的下面部分:

        if (mTitleTextView != null) {
            mTitleTextView.setText(title);
        }

此时,Title被重新设置为我们自定义的Title。
程序继续执行,发现在TextView.java里面有个方法比较奇怪:

    /**
     * Makes the TextView at least this many pixels tall.
     *
     * Setting this value overrides any other (minimum) number of lines setting.
     *
     * @attr ref android.R.styleable#TextView_minHeight
     */
    @android.view.RemotableViewMethod
    public void setMinHeight(int minHeight) {
        mMinimum = minHeight;
        mMinMode = PIXELS;

        requestLayout();
        invalidate();
    }

这里面有个invalidate();,点进去发现

     * @param invalidateCache Whether the drawing cache for this view should be
     *            invalidated as well. This is usually true for a full
     *            invalidate, but may be set to false if the View's contents or
     *            dimensions have not changed.
     */
    void invalidate(boolean invalidateCache) {
        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
    }

终于发现这个问题的原因在哪里,原来在这里程序调用了invalidate();方法,将我们自定义的Title的高度设为0,所以自定义的Title没有显示。

到此为止,这个问题的原因找到了,所以正确的用法是在setSupportActionBar方法之前把需要设置的ToolBar里面的参数全部设置完毕,再调用该方法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容