10

我在我的项目中使用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它不能为空并且必须参考一些观点。如果您删除setRetainInstance(true)并保留片段,则每次此问题消失时都会重新创建。有什么想法可能导致这个问题吗?

4

3 回答 3

15

UPD:问题现已解决。您不必再clearFindViewByIdCache()手动调用。

View调用后不清除缓存onDestroyView()。有一个未解决的问题

现在,您可以显式调用clearFindViewByIdCache()inonDestroyView()来清除缓存。此方法是synthetic包的一部分,因此您必须导入它

import kotlinx.android.synthetic.*
于 2015-07-03T15:14:04.557 回答
7

只是为了澄清。现在问题已解决。您不必再通过 clearFindViewByIdCache() 了。请查看问题跟踪器:https ://youtrack.jetbrains.com/oauth?state=%2Fissue%2FKT-8073

于 2015-10-15T14:05:37.160 回答
6

我自己找到了答案。该类Fragment不会直接膨胀布局——它具有view: View?保存它的属性。这应该很明显,因为它是用onCreateView. 为了访问其中的属性,view您必须设置导入

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

然后按如下方式访问属性

view?.text_view?.setText(text)

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

于 2015-07-02T15:21:05.930 回答