I was previously using 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.
But I am not sure how to use ViewBinding for view_error.xml
here to access btnRetry
of view_error.xml?
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. something like this
in 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. Something like given below.
binding.retryLayoutId.btnRetry.setOnClickListener {
viewModel.retryRecipeRequest(args.id)
}
where layoutId is the included layout's id.