Search code examples
androidkotlinandroid-recyclerviewonclicklistenerandroid-viewmodel

How to use the recycler view as a (tab layout) to update fragment layout with user info


I want to achieve this

My goal is that when user click on the person it the change the text color to blue and it will show the personal information and it will be same for all the users. so I am trying to use recycler view with single fragment.

when user clicks on the **Button Increment ** it will update the person count in recycler view.

when user switch between deferent person I want to show that person information without creating new fragment.

I tried using the tab layout and view-pager but the layout is same for all the users so I think there should be a better way to approach this.

should I pass viewmodle to my adapter and observe the button click count?

this problem has 3 main question.

  1. should I pass the view model to update the recycler-view data?
  2. how to approach when different person is click should I create new fragment and apply the data again or should I user single view model to show the person data?
  3. how to hand click when user clicks on the increment button and how pass the data back to update the increment count in recycler view.

[Image to achieve this result


Solution

  • Yes a simple way to start is to have 1 viewModel that is passed into the adapter and as well as to the fragment.

    Let’s start simple and get it working with just 3 peoples data. In your view model you should then have:

    val person1 = mutableLiveData<Person>()
    val person2 = mutableLiveData<Person>()
    val person3 = mutableLiveData<Person>()
    
    init {
        person1.value = Person()
        …
    }
    

    Then if you pass the viewModel to the the adapter, you can have:

    veiwModel.person1.observe { updatedPerson ->
        dataset.removeAt(0)
        dataset.addItemAtPosotion(updatedPerson, 0)
        [email protected](0)
    }
    

    In your fragment you can similarly observe a new piece of live data call fragmentPerson and reinitialize the fragment when that data changes.