繁体   English   中英

如何在DialogFragment中正确使用Android视图绑定?

[英]How to correctly use Android View Binding in DialogFragment?

在 DialogFragment() 中使用 Android 视图绑定的正确方法是什么?

官方文档只提到了Activity和Fragment: https://developer.android.com/topic/libraries/view-binding

请改用inflate(LayoutInflater.from(context)) 并使用binding.root设置构建器视图。

此外,正如 Google 所建议的,在使用片段时,最好在onDestroyView()binding实例设置为 null: https://developer.android#fragments.com。

例子:

class ExampleDialog : DialogFragment() {

    private var _binding: DialogExampleBinding? = null
    // This property is only valid between onCreateDialog and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        _binding = DialogExampleBinding.inflate(LayoutInflater.from(context))
        return AlertDialog.Builder(requireActivity())
            .setView(binding.root)
            .create()
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    } 
}

使用视图绑定在对话框中设置适配器

  1. 使用 CamelCase 中的 xml 名称并带有后缀 Binding。 变量名由xml决定: fragment_dialog_location_change.xml

  2. 注意编译时对话框 object 的 class 中定义的命名法: FragmentDialogLocationChangeBinding


private lateinit var binding: FragmentDialogLocationChangeBinding
private lateinit var lastLocationsAdapter: LastLocationsAdapter

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    binding = FragmentDialogLocationChangeBinding.inflate(LayoutInflater.from(context))

    // The adapter could also be set before returning the dialog

    return activity?.let {
        val builder = AlertDialog.Builder(it)

        builder.setTitle("Change location")
        builder.setView(binding.root)
        builder.setMessage("Last searched")

        builder.setPositiveButton("New Search") { dialogInterface: DialogInterface, i: Int ->
           // action
        }

        builder.create()
    } ?: throw IllegalStateException("Activity cannot be null")
}

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    lastLocationsAdapter = LastLocationsAdapter()
    binding.listRecyclerView.adapter = lastLocationsAdapter

    return binding.root
}

资源

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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