[英]How to pass data from clicked item in recyclerview to viewmodel and open new activity?
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? 如何正确地在android中的
MVVM
中传递文本和id单击一个项目到ViewModel
并打开新活动?
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.
因此,当我单击该项目时,我想显示新活动以及所单击项目的数据,并且需要项目ID来编辑该项目中的对象。
Using the RecyclerView.Adapter to populate your data, implement OnClickListener to viewHolder. 使用RecyclerView.Adapter填充数据,实现OnClickListener到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. 在onClick方法(重写)上,您可以键入代码以开始新的活动,假设您有一个名为Test的模型类,以及一个名为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. 请注意,getAdapterPosition()将返回您单击的位置,mContext是上下文传递给适配器的。
You will need your model class to implement Parcelable to allow model to be transferred between activities. 您将需要模型类来实现Parcelable,以允许在活动之间传递模型。 https://developer.android.com/guide/components/activities/parcelables-and-bundles
https://developer.android.com/guide/components/activities/parcelables-and-bundles
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.