Kotlin Android扩展和保留片段

我在项目中使用Kotlin Android扩展 ,遇到了一些我无法理解的行为。 我使用这段代码来保留我的片段:

val fragment = fragmentManager.findFragmentByTag("hello") ?: HelloFragment() fragmentManager.beginTransaction() .replace(R.id.fragment_container, fragment, "hello") .commit() 

这是保留的Fragment

 import kotlinx.android.synthetic.hello.* public class HelloFragment : Fragment() { val text = "Hello world!" override fun onCreate(savedInstanceState: Bundle?) { super<Fragment>.onCreate(savedInstanceState) setRetainInstance(true) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.hello, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super<Fragment>.onViewCreated(view, savedInstanceState) text_view.setText(text) // <- does not work when retained } } 

和它的XML布局hello.xml

 <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text_view" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" /> 

一切都按预期工作 – text_view.setText()显示Hello world! 在第一次启动屏幕上。 但是,当你旋转屏幕text_view.setText()不起作用。 这很奇怪,因为text_view是不可空的,必须text_view一些观点。 如果删除了setRetainInstance(true)并且每当此问题消失时都将重新创建片段。 有什么想法可能会导致这个问题?

UPD:这个问题现在已经解决了。 您不必手动调用clearFindViewByIdCache()

调用onDestroyView()后, View缓存不会被清除。 有一个公开的问题 。

现在,您可以显式调用onDestroyView() clearFindViewByIdCache() onDestroyView()来清除缓存。 这种方法是synthetic软件包的一部分,所以你必须导入它

 import kotlinx.android.synthetic.* 

只是为了澄清。 这个问题现在已经解决了。 您不必再传递clearFindViewByIdCache()。 请参阅问题跟踪器: https : //youtrack.jetbrains.com/oauth? state =% 2Fissue%2FKT- 8073

我自己找到了答案。 Fragment类不直接膨胀布局 – 它有属性view: View? 持有它。 这应该是非常明显的,因为它是用onCreateView创建的。 为了访问view内的属性,你必须设置导入

 import kotlinx.android.synthetic.hello.view.* 

然后按如下方式访问属性

 view?.text_view?.setText(text) 

请注意,这些属性是可以为空的。