java – 导航抽屉 – syncState()做什么以及为什么应该在onPostCreate()上调用?

我正在学习在Android中创建导航抽屉。在阅读this时,我无法理解以下代码:

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    mDrawerToggle.syncState();
}

文件说:

Synchronize the state of the drawer indicator/affordance with the
linked DrawerLayout.

This should be called from your Activity’s onPostCreate method to
synchronize after the DrawerLayout’s instance state has been restored,
and any other time when the state may have diverged in such a way that
the ActionBarDrawerToggle was not notified. (For example, if you stop
forwarding appropriate drawer events for a period of time.)

此外,我从sstn的答案hereOnPostCreate in Fragment读了关于onPostCreate()

onPostCreate() is mainly intented for framework use (although you can
override it). The docs say that it is called after onStart() and
onRestoreInstanceState().

This might lead to the assumption that it might be called before
onResume() and thus probably before the message loop is dispatching
events (including AsyncTask’s onPostExecute() method), meaning your
onPostExecute() will only fire after onPause().

As onPostCreate() is not properly documented and not really intended
for application use – I might want to say it is not a good idea to
rely on any observed behaviour.

从这两个我不明白什么。 syncState()究竟做什么以及为什么应该在onPostcreate()中?任何人都可以解释更好吗?

那么我认为这个问题是一个很好的问题。我会收集这个问题及其答案。所以,我们在这里做一些总结:

首先,对于ActionBarDrawerToggle.syncState(),正如文档所说,

Synchronize the state of the drawer indicator/affordance with the
linked DrawerLayout.

This should be called from your Activity‘s onPostCreate method to
synchronize after the DrawerLayout‘s instance state has been
restored, and any other time when the state may have diverged in such
a way that the ActionBarDrawerToggle was not notified. (For example,
if you stop forwarding appropriate drawer events for a period of
time.)

第二,对于Activity.onPostCreate(Bundle),当活动启动完成(在onStart()和onRestoreInstanceState(Bundle)被调用之后)时调用它。申请一般不会实行这种方法;它是为系统类在应用程序代码运行后进行最终初始化。

但是,派生类必须调用这个超类来实现这个方法。如果没有,将抛出异常。

那么syncState()究竟做了什么呢?

那么ActionBarDrawerToggle.syncState()将同步改变后的图标的状态,这个状态取决于DrawerLayout的动作。如果你曾经尝试删除syncState(),你会发现箭头的图标不会再旋转了。

为什么syncState()应该在onPostcreate()中调用?

那么在活动启动完成之后(在onStart()和onRestoreInstanceState(Bundle)被调用)之后调用onPostcreate(),而Activity当前需要动画来准备工作。那么,如果它不是动画的最佳时刻,那是什么时候呢?

http://stackoverflow.com/questions/29999299/navigation-drawer-what-does-syncstate-do-and-why-it-should-be-called-inside

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java – 导航抽屉 – syncState()做什么以及为什么应该在onPostCreate()上调用?