简体   繁体   中英

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

}


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM