在我的片段中,我有一些图像和视图,它们通过绑定数据来获取其值,并在其下方有一个RecyclerView。图片和文本视图成功显示,但我的Recyclerview无法显示。如果仅返回视图,则显示RecyclerView,但不显示绑定的数据。我想同时查看它们。
[]
class DetailFragment : Fragment(), LessonRecyclerAdapter.LessonItemListener {
private lateinit var viewModel: SharedViewModel
private lateinit var recyclerView: RecyclerView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_detail, container, false)
recyclerView = view.findViewById(R.id.lessonRecyclerView)
navController = Navigation.findNavController(requireActivity(), R.id.nav_host )
viewModel = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
viewModel.lessonData.observe(viewLifecycleOwner, Observer {
val adapter =
LessonRecyclerAdapter(
it,
this
)
recyclerView.adapter = adapter
})
// return binding data
val binding = FragmentDetailBinding.inflate(inflater, container, false)
binding.lifecycleOwner = this
binding.viewModel = viewModel
return binding.root
//return view
}
答案 0 :(得分:1)
您会看到,有两种膨胀,一种用于绑定,另一种用于视图(用于recyclerview设置)。简单的解决方案是直接使用绑定变量中的recyclerview
将列表设置为:
private lateinit var binding: FragmentDetailBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
navController = Navigation.findNavController(requireActivity(), R.id.nav_host )
viewModel = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
binding = FragmentDetailBinding.inflate(inflater, container, false)
binding.lifecycleOwner = this
binding.viewModel = viewModel
viewModel.lessonData.observe(viewLifecycleOwner, Observer {
val adapter =
LessonRecyclerAdapter(
it,
this
)
// directly access the view using ids
binding.lessonRecyclerView.adapter = adapter
})
return binding.root
}
另一种选择是use binding adapters使用实时数据来设置适配器并将数据传递到适配器。