Search code examples
androidandroid-layoutandroid-fragmentsandroid-viewbinding

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.

Here are the relevant files:

  • view_error.xml (other layout XML)
  • RecipeDetailFragment.kt
  • fragment_recipe_detail.xml (corresponding Fragment XML)

Previous Code in short (Using Kotlin Synthetics)

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)
    }

}

Current Code Attempt in short: (Using ViewBinding)

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)
    }

}



Solution

  • 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.