最近在android開發(fā)過程中遇到了一個(gè)小的問題,就是ToolBar的setTitle方法和setSupportActionBar方法之間會(huì)有沖突的問題,問題如下:
如果在setSupportActionBar之后設(shè)置setTitle,則后者沒有任何效果,如下圖所示
如果在之前設(shè)置setTitle,則Title可以順利顯示。
本著究其根本的緣故,遂深入源碼查詢原因。
setSupportActionBar和getSupportActionBar是設(shè)置ActionBar的主要方法,是AppCompatActivity的public 方法之一。其主要用來設(shè)置ToolBar,至于ToolBar的知識(shí)就更多了,在此不多贅述。
我們來看API文檔:

從 Android 3.0(API 級(jí)別 11)開始,所有使用默認(rèn)主題的 Activity 均使用 [ActionBar](https://developer.android.com/reference/android/app/ActionBar.html)
作為應(yīng)用欄。不過,經(jīng)過不同 Android 版本的演化,應(yīng)用欄功能已逐漸添加到原生 [ActionBar](https://developer.android.com/reference/android/app/ActionBar.html)
中。因此,原生 [ActionBar](https://developer.android.com/reference/android/app/ActionBar.html)
的行為會(huì)隨設(shè)備使用的 Android 系統(tǒng)的版本而發(fā)生變化。相比之下,最新功能已添加到支持庫版本的 [Toolbar](https://developer.android.com/reference/android/support/v7/widget/Toolbar.html)
中,并且這些功能可以在任何能夠使用該支持庫的設(shè)備上使用。
因此,您應(yīng)使用支持庫的 [Toolbar](https://developer.android.com/reference/android/support/v7/widget/Toolbar.html)
類來實(shí)現(xiàn) Activity 的應(yīng)用欄。使用支持庫的工具欄有助于確保您的應(yīng)用在最大范圍的設(shè)備上保持一致的行為。例如,[Toolbar](https://developer.android.com/reference/android/support/v7/widget/Toolbar.html)
小部件能夠在運(yùn)行 Android 2.1(API 級(jí)別 7)或更高版本的設(shè)備上提供 [Material Design](https://developer.android.com/design/material/index.html) 體驗(yàn),但除非設(shè)備運(yùn)行的是 Android 5.0(API 級(jí)別 21)或更高版本,否則原生操作欄不會(huì)支持 Material Design.
在 Activity 的 [onCreate()](https://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle))
方法中,調(diào)用 Activity 的 [setSupportActionBar()](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html#setSupportActionBar(android.support.v7.widget.Toolbar))
方法,然后傳遞 Activity 的工具欄。該方法會(huì)將工具欄設(shè)置為 Activity 的應(yīng)用欄。例如:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
}
您的應(yīng)用現(xiàn)在具有一個(gè)基本操作欄。默認(rèn)情況下,操作欄只包含應(yīng)用的名稱和一個(gè)溢出菜單。選項(xiàng)菜單最初只包含 **Settings** 菜單項(xiàng)。您可以按照[添加和處理操作](https://developer.android.com/training/appbar/actions.html)中所述向操作欄和溢出菜單添加更多操作
默認(rèn)情況下,操作欄只包含應(yīng)用的名稱和一個(gè)溢出菜單。
這里有個(gè)小坑,就是默認(rèn)情況下,ToolBar上的應(yīng)用名是會(huì)顯示的,如果沒有對ToolBar設(shè)置setTitle,則默認(rèn)使用應(yīng)用名。并且如果在setSupportActionBar之后設(shè)置setTitle,則設(shè)置無效,仍然顯示應(yīng)用名。
那么,這還是沒有解決問題,我們從源碼來看(附:最機(jī)智的源碼查看方式,就是加個(gè)斷點(diǎn),然后調(diào)試采用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之前就設(shè)置了Title,則運(yùn)行到setSupportActionBar(mToolBar);這里,由于判空函數(shù)返回true,則自動(dòng)跳過這段程序,即setSupportActionBar不執(zhí)行設(shè)置Title,此為正確設(shè)置Title狀態(tài)。
而如果setSupportActionBar在setTitle之前,則把Title默認(rèn)設(shè)置為應(yīng)用名。
此時(shí)進(jìn)入setTilte方法,由于mTitleTextView不為空,程序運(yùn)行到最后,mTitleText = title;,即setTitle正確設(shè)置了Title,但是為什么沒有顯示新的Title,仍然顯示默認(rèn)的應(yīng)用名呢?
這是本文的重點(diǎn)部分。
(1)setSupportActionBar在setTitle之前,把Title默認(rèn)設(shè)置為應(yīng)用名
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();
}
通過調(diào)試發(fā)現(xiàn),在上述代碼中
final ToolbarActionBar tbab = new ToolbarActionBar(toolbar,
((Activity) mOriginalWindowCallback).getTitle(), mAppCompatWindowCallback);
設(shè)置了Title為默認(rèn)的應(yīng)用名。點(diǎn)進(jìn)去看看代碼如下;
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;
}
這里可以發(fā)現(xiàn),如果返回的是個(gè)Activity,則使用它的標(biāo)題,即是默認(rèn)的應(yīng)用名,這個(gè)在設(shè)置Menu菜單的時(shí)候可以發(fā)現(xiàn)。

如上圖,在左上角的標(biāo)題即是默認(rèn)的應(yīng)用名。
(2)之后通過setTitle設(shè)置Title,為什么沒有反應(yīng)呢?
調(diào)試程序跳轉(zhuǎn)到setTitle的下面部分:
if (mTitleTextView != null) {
mTitleTextView.setText(title);
}
此時(shí),Title被重新設(shè)置為我們自定義的Title。
程序繼續(xù)執(zhí)行,發(fā)現(xiàn)在TextView.java里面有個(gè)方法比較奇怪:
/**
* 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();
}
這里面有個(gè)invalidate();,點(diǎn)進(jìn)去發(fā)現(xiàn)
* @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);
}
終于發(fā)現(xiàn)這個(gè)問題的原因在哪里,原來在這里程序調(diào)用了invalidate();方法,將我們自定義的Title的高度設(shè)為0,所以自定義的Title沒有顯示。
到此為止,這個(gè)問題的原因找到了,所以正確的用法是在setSupportActionBar方法之前把需要設(shè)置的ToolBar里面的參數(shù)全部設(shè)置完畢,再調(diào)用該方法。