我从setActionBar
的{{1}}方法中发现了这一点:
Activity
正如您所看到的,public void setActionBar(@Nullable Toolbar toolbar) {
final ActionBar ab = getActionBar();
if (ab instanceof WindowDecorActionBar) {
throw new IllegalStateException("This Activity already has an action bar supplied " +
"by the window decor. Do not request Window.FEATURE_ACTION_BAR and set " +
"android: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, getTitle(), this);
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(this);
}
invalidateOptionsMenu();
}
通过包装的回调被调用。如果我们检查mWindow.setCallback(tbab.getWrappedWindowCallback())
的实施情况:
ToolbarAractionBar
它包装了构造函数的最后一个参数,即ToolbarActionBar(Toolbar toolbar, CharSequence title, Window.Callback windowCallback) {
mDecorToolbar = new ToolbarWidgetWrapper(toolbar, false);
mWindowCallback = new ToolbarCallbackWrapper(windowCallback);
mDecorToolbar.setWindowCallback(mWindowCallback);
toolbar.setOnMenuItemClickListener(mMenuClicker);
mDecorToolbar.setWindowTitle(title);
}
public Window.Callback getWrappedWindowCallback() {
return mWindowCallback;
}
(this
的实例)。
如果在调用Activity
之前设置了我们自己的setActionBar
实现(正确包装了原始实现),就会出现问题。在这种情况下,我们的实现不是由Window.Callback
包装,而是由原始包装。
如果使用ToolbarActionBar
而不是getWindow().getCallback()
作为this
构造函数参数,这不会有问题。因此,它看起来像是android sdk中的错误。
问题是:有人知道如何处理这种情况或解决该问题的方法吗? (让我们假设我们应该在添加操作栏之前设置回调)
顺便说一句。 ToolbarActionBar
看起来不一样,但非常相似,并且有相同的问题。