[英]How to use ViewBinding when referencing view IDs from "other" layout XML i.e, not the corresponding Fragment XML?
I was previously using Kotlin Synthetics.我以前使用的是 Kotlin Synthetics。
Here are the relevant files:以下是相关文件:
import kotlinx.android.synthetic.main.view_error.*
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_recipe_detail, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
...
// btnRetry is from view_error.xml. Accessed using Kotlin Synthetics
btnRetry.setOnClickListener {
viewModel.retryRecipeRequest(args.id)
}
}
So, here I successfully used ViewBinding for corresponding Fragment layout.所以,这里我成功地使用了 ViewBinding 来进行相应的 Fragment 布局。
But I am not sure how to use ViewBinding for view_error.xml
here to access btnRetry
of view_error.xml?但我不确定如何在此处使用 ViewBinding for
view_error.xml
来访问btnRetry
的 btnRetry?
What code is required to be added below?下面需要添加什么代码?
import com.packagename.databinding.FragmentRecipeDetailBinding
private var _binding: FragmentRecipeDetailBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentRecipeDetailBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
...
// NOW THE btnRetry gives error as I removed the kotlin synthetics imports.
// How to access btnRetry through ViewBinding?
btnRetry.setOnClickListener {
viewModel.retryRecipeRequest(args.id)
}
}
You must be using <include>
element to use the external layout within fragment_recipe_detail.您必须使用
<include>
元素才能使用 fragment_recipe_detail 中的外部布局。 something like this像这样的东西
in fragment_recipe_detail.xml在 fragment_recipe_detail.xml
<include
android:id="@+id/retryLayoutId"
layout="@layout/retryLayout"
/>
So now in the case of view binding you can access the viewbinding variable and access the external layout id and then access its children.因此,现在在视图绑定的情况下,您可以访问视图绑定变量并访问外部布局 ID,然后访问其子项。 Something like given below.
如下所示。
binding.retryLayoutId.btnRetry.setOnClickListener {
viewModel.retryRecipeRequest(args.id)
}
where layoutId is the included layout's id.其中 layoutId 是包含的布局的 ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.