user13409565
user13409565

Reputation:

Return either binding data or recycler view problem

Inside my fragment, i have some image and views that are getting their values by binding data, and beneath them a RecyclerView. The images and textviews are showing successfully but my Recyclerview won't show. If i return my view only, the RecyclerView shows but the binded data doesn't. I want to view both of them.

[enter image description here]

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
    }

Upvotes: 1

Views: 43

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

As you can see, There are two inflates, one for binding and another for view(for recyclerview setup). The easy solution is to directly use recyclerview from binding variable to set up the list as:

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
    }

Another option is to use binding adapters with live data to setup adapter and pass the data to the adapter.

Upvotes: 1

Related Questions