kotlin 如何通过viewBinding使用参数化的AppCompatActivity(R.layout.activity_main)?

xxhby3vn  于 2023-04-12  发布在  Kotlin
关注(0)|答案(3)|浏览(171)

我知道如何使用参数化的Fragment(R.layout.fragment_dummy),并将其视图与viewBinding绑定并使用它。如下面的代码所示

但我不知道如何以类似的方式使用参数化活动。

nzkunb0c

nzkunb0c1#

绑定应该发生在onCreateView中,然后返回binding.root

private var someBinding: SomeBinding? = null

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    someBinding = SomeBinding.inflate(layoutInflater)
    return someBinding!!.root
}

override fun onDestroyView() {
    someBinding = null
    super.onDestroyView()
}

Activity中,您正在使用onCreate方法中的绑定,并使用setContentView(binding.root)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = SomeBinding.inflate(layoutInflater)
    setContentView(binding.root)

您不必在Activity中保留对binding的引用(因为当布局主机被破坏时,并不强制释放/清理它),但它可能在以后设置View的属性时有用;)

zsohkypk

zsohkypk2#

对于带ViewBinding的Fragment,它没有可能的参数,但您可以使用如下所示

class DemoFragment : Fragment() {
    private var mBinding: FragmentDemoBinding? = null;

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        mBinding = FragmentDemoBinding.inflate(layoutInflater)
        return mBinding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }
}
pcrecxhr

pcrecxhr3#

这里有一个从android studio本身生成的代码。
用于活动

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

对于片段

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

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {

    _binding = FragmentHomeBinding.inflate(inflater, container, false)
    return binding.root
}

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}

通过访问视图

binding.textView

相关问题