gpt4 book ai didi

java - Navigation Drawer - syncState() 做什么以及为什么应该在 onPostCreate() 中调用它?

转载 作者:IT老高 更新时间:2023-10-28 20:29:12 24 4
gpt4 key购买 nike

我正在学习在 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 的回答 here 中进一步了解了 onPostCreate() : OnPostCreate in Fragment

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)在activity启动完成时调用(在onStart()onRestoreInstanceState(Bundle) 已被调用)。应用程序一般不会实现此方法;它旨在让系统类在应用程序代码运行后进行最终初始化。

但是,派生类必须调用到父类(super class)的实现这个方法。如果不这样做,就会抛出异常。

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

嗯,ActionBarDrawerToggle.syncState() 将同步更改后的图标状态,这取决于 DrawerLayout 的操作。如果您曾尝试删除 syncState(),您会发现箭头图标不再旋转。

为什么要在onPostcreate()中调用syncState()

好吧,onPostcreate() 会在 Activity 启动完成时调用(在 onStart()onRestoreInstanceState(Bundle) 完成之后调用),而目前,Activity 需要动画才能工作。那么,如果现在不是动画的最佳时刻,那是什么时候呢?

关于java - Navigation Drawer - syncState() 做什么以及为什么应该在 onPostCreate() 中调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29999299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com