如何在从 "other" 布局 XML 引用视图 ID 时使用 ViewBinding,即,而不是相应的 Fragment XML?

How to use ViewBinding when referencing view IDs from "other" layout XML i.e, not the corresponding Fragment XML?

我之前使用的是 Kotlin Synthetics。

相关文件如下:

前一代码简述(使用 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)
    }

}

当前代码尝试简而言之:(使用 ViewBinding)

所以,这里我成功的使用ViewBinding进行了相应的Fragment布局

但我不确定如何在此处使用 view_error.xml 的 ViewBinding 来访问 view_error.xml 的 btnRetry?

下面需要添加什么代码?

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

}


您必须使用 <include> 元素才能在 fragment_recipe_detail 中使用外部布局。像这样

在fragment_recipe_detail.xml

   <include
    android:id="@+id/retryLayoutId"
    layout="@layout/retryLayout"
    />

所以现在在视图绑定的情况下,您可以访问视图绑定变量并访问外部布局 ID,然后访问其子项。如下所示。

binding.retryLayoutId.btnRetry.setOnClickListener {
            viewModel.retryRecipeRequest(args.id)
        }

其中 layoutId 是包含布局的 ID。