在视图中实现不同片段中的相同数据绑定布局可以通过以下方法解决:
shared_layout.xml
的文件中定义一个包含数据绑定元素的线性布局。
shared_layout.xml
布局文件,并定义与该布局文件中的数据绑定元素相同的变量名称。
// FragmentOne.kt
class FragmentOne : Fragment() {
private lateinit var binding: FragmentOneBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentOneBinding.inflate(inflater, container, false)
binding.item = MyItem("Title One", "http://example.com/image1.jpg")
return binding.root
}
}
// FragmentTwo.kt
class FragmentTwo : Fragment() {
private lateinit var binding: FragmentTwoBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentTwoBinding.inflate(inflater, container, false)
binding.item = MyItem("Title Two", "http://example.com/image2.jpg")
return binding.root
}
}
这样,两个片段都会使用相同的布局,并根据提供的数据进行相应的数据绑定。