有没有更聪明的方法将布局绑定到片段?

Posted

技术标签:

【中文标题】有没有更聪明的方法将布局绑定到片段?【英文标题】:Is there a smarter way to bind layouts to fragments? 【发布时间】:2021-06-16 16:37:33 【问题描述】:

我有一个片段的两个 XML 布局。代码必须在要绑定到的两个布局中进行选择。目前,这是我的代码。

这里,我声明了两个布局绑定。

private var bindingVariation: FragmentStartVariationBinding? = null
private var binding: FragmentStartBinding? = null

在 onCreateView 中,代码检查将要绑定到哪个布局。

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? 
        if(sharedViewModel.discountEnabled.value == true)
            val fragmentBinding = FragmentStartVariationBinding.inflate(inflater, container, false)
            bindingVariation = fragmentBinding
            bindingVariation?.startFragment = this
            bindingVariation?.viewModel = sharedViewModel
            return fragmentBinding.root
        else
            val fragmentBinding = FragmentStartBinding.inflate(inflater, container, false)
            binding = fragmentBinding
            binding?.startFragment = this
            return fragmentBinding.root
        
    

这个 hack 目前有效,但如果我想在类中的其他地方调用绑定,我必须每次都检查它的绑定或绑定变化。

这段代码自然不起作用,但很好地说明了我想要实现的目标。

private var binding = setBinding()

fun setBinding()
   var exampleBinding? = null
   if(sharedViewModel.discountEnabled.value == true)
      return exampleBinding: FragmentStartVariationBinding? = null
   else
      return exampleBinding: FragmentStartBinding? = null
   

【问题讨论】:

我个人的建议是你应该只制作两个不同的片段,每个片段都有自己合适的布局 欢迎来到 Stack Overflow!是的@a_local_nobody 是对的,你应该有两个片段,并根据你的情况决定显示哪一个。 【参考方案1】:

最好的方案是为每个布局分开你的片段,但如果你需要在一个片段中处理多布局绑定,请这样做:

1 .声明你的多重绑定:

    lateinit var bindingLarge : FragmentProfileLargeScreenBinding
    lateinit var binding : FragmentProfileBinding

2 。分配他们:

    if (...) 
        bindingLarge = FragmentProfileLargeScreenBinding.inflate(layoutInflater)
        return R.layout.fragment_profile_large_screen
    
    else 
        binding = FragmentProfileBinding.inflate(layoutInflater)
        return R.layout.fragment_profile
    

3 .声明这样的视图:

fun getTextWithdrawal() : Button 
    return if(this::binding.isInitialized)
        binding.textWithdrawal
    else
        bindingLarge.textWithdrawal

4 .使用视图:

getTextWithdrawal().setOnClickListener ...
getTextWithdrawal().visibility = View.Visible
getTextWithdrawal(). ...

【讨论】:

以上是关于有没有更聪明的方法将布局绑定到片段?的主要内容,如果未能解决你的问题,请参考以下文章

有没有啥聪明的方法可以在 python 中组合重叠路径?

WPF命令行参数,一种聪明的方法?

巴菲特公式:如何通过阅读变得更聪明

有没有聪明的方法来解析 xml 到列表?

巴菲特公式:如何通过阅读变得更聪明

C/C++ 需要一种聪明的方法来跟踪函数调用