用recremview()初始化视图绑定
最近,我喜欢使用requireview()
懒惰地初始化我的视图绑定。
为了详细说明,我倾向于写这篇文章:
class ExampleFragment : Fragment() {
private val binding by lazy { FragmentExampleBinding.bind(requireView()) }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// make use of binding
}
}
...而不是这样:
class ExampleFragment : Fragment() {
private lateinint var binding: FragmentExampleBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding = FragmentExampleBinding.bind(view)
// make use of binding
}
}
在我看来,它有点干净(尽管它只是节省了一条或两行)。但是,我还没有看到它在任何地方都使用,这是一个实际的问题: 这种方法有问题吗?我有什么忽略的吗?
注意:我可以看到IE首次使用绑定
。 coroutine可能会导致requieview()
被杀死(因此扔了illegalstateException
)。不过,这似乎并不令人担忧,因为片段的所有coroutines都应在其view> view lifecycleowner
下被称为“ ”,因此不应该超越它。
Lately I have become fond of initializing my view bindings lazily using requireView()
.
To elaborate, I tend to write this:
class ExampleFragment : Fragment() {
private val binding by lazy { FragmentExampleBinding.bind(requireView()) }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// make use of binding
}
}
... instead of this:
class ExampleFragment : Fragment() {
private lateinint var binding: FragmentExampleBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding = FragmentExampleBinding.bind(view)
// make use of binding
}
}
It feels to me a bit cleaner (although it just saves one or two lines). However, I haven't seen this being used anywhere, which makes come to the actual question:
Is there something wrong with this approach? Is there anything I have overlooked?
Note: I can see that making use of binding
for the first time in ie. a coroutine might cause requireView()
to be called after the fragment has been killed (and thus throw an IllegalStateException
). It doesn't seem too concerning to me though, as all coroutines for the fragment should be called "under" its viewLifecycleOwner
and therefore shouldn't outlive it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当碎片的视图被破坏时,您的两个示例在技术上泄漏了您的观点。如果您不在乎,除了使用属性代表和Lazy的默认线程安全模式的某些无关紧要的开销外,您的执行版本并不比使用
LateInit
更糟糕。有些争论(请参阅ondestroyview部分从碎片中,因为碎片实例仅暂时生活在被破坏的国家中。有关更多信息,请参见这个问题。
实际上,无论如何,我都不需要使用绑定外部
onviewCreated
,因此我只使用局部变量而不是属性。Both of your examples technically leak your views when the Fragment's view is destroyed. If you don't care about that, your version of doing it is no worse than using
lateinit
, aside from some insignificant overhead from the property delegate and Lazy's default thread-safety mode.Some argue (see onDestroyView section) that it doesn't matter if you leak views from a Fragment, because the Fragment instance lives in a destroyed state only temporarily. For more information, see this question.
In practice, I never need to use the binding outside
onViewCreated
anyway, so I just use a local variable instead of a property.