Search code examples
androidandroid-fragmentsandroid-adapterandroid-livedataandroid-viewmodel

How to apply changes on current fragment when opening new fragment in Kotlin?


I have managed to switch between fragment, but the changes on current fragment doesn't applied when entering a new fragment. I have 2 fragments, HomeFragment and Sublisting. When I first run the app, it shows HomeFragment which is showing football content. If I click action bar, it will change into Subreddit fragment. In Sublisting fragment, I can click a subreddit category (e.g. basketball, tennis, etc.). After I click a subreddit category, the fragment change to HomeFragment again where it should shows the content of subreddit category I just choose, but it doesn't. I choose tennis while in Sublisting fragment, but it still showing the first subreddit category when I run my app, which is football.

Here is my SublistingListAdapter.kt

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
    val binding = RowSubredditBinding.inflate(LayoutInflater.from(parent.context),
        parent, false)
    val holder = VH(binding)
    
    return holder
}

Here is my HomeFragment.kt:

class HomeFragment: Fragment() {
    private val viewModel: MainViewModel by viewModels()
    private var _binding: FragmentRvBinding? = null
    private val binding get() = _binding!!

    companion object {
        fun newInstance(): HomeFragment {
            return HomeFragment()
        }
    }
   
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentRvBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.d(javaClass.simpleName, "onViewCreated")

        initAdapter(binding)
    }
}

I thought by using updateNewCategory and observeNewCategory would change the subreddit category, but turns out it didn't. How to update the category and apply the changes?


Solution

  • What I am understanding with your code snippet is that your are trying to use common MainViewModel to communicate among your fragments and Activity.

    Your issue is that you are creating new instance of MainViewModel in your fragment by using private val viewModel: MainViewModel by viewModels() instead of using activityViewModel

    Use following line to get viewModel reference of your activity in your fragment

    private val viewModel: MainViewModel by activityViewModels()