How to pass data from clicked item in recyclerview to viewmodel and open new activity?

Viewed 1205

As I wrote, I'm looking the solution to that problem. How to correctly in MVVM in Android pass texts and id clicked an item to ViewModel and open new activity?

The new activity is a detail of item. So when I click on the item I want to display new activity with data from the clicked item and I need item id to edit the object in the item.

1 Answers

Using the RecyclerView.Adapter to populate your data, implement OnClickListener to viewHolder.

At onClick Method (overridden) you can type your code to start new activity, lets say you have model class called Test, and array list called testList. then:

Intent intent = new Intent(mContext, DetailActivity.class);
intent.putExtra(KEY, testList.get(getAdapterPosition()));
mContext.startActivity(intent);

Note that getAdapterPosition() will return the position where you clicked, mContext is context passed to adapter.

You will need your model class to implement Parcelable to allow model to be transferred between activities. https://developer.android.com/guide/components/activities/parcelables-and-bundles

Related