我有一个 POJO
类。它包含一些字符串,我想将值从 RecyclerView
传递到 Activity
。我尝试了一些但失败了。我该怎么做?
Model
public class DetailModel {
String title;
public DetailModel() {
}
public DetailModel(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Adapter, onClick
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
detailModel=new DetailModel();
detailModels= new ArrayList<>();
detailModel.setTitle(holder.headerText.getText().toString());
Intent detailIntent = new Intent(context.getApplicationContext(), DetailActivity.class);
context.startActivity(detailIntent);
}
});
Another Activity
DetailModel detailModel=new DetailModel();
detailBody.setText(detailModel.getTitle());
最佳答案
有几种方法可以做到这一点,但我将向您展示最简单的一种:
在你的 onBindViewHolder
中:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder,final int position) {
final MyView myHolder = (MyView) holder;
myHolder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
detailModel.setTitle(holder.headerText.getText().toString());
Intent detailIntent = new Intent(context, DetailActivity.class);
//To pass your class:
intent.putExtra("mypojo", details.get(position));
context.startActivity(detailIntent);
}
});
}
以这种方式,您必须在您的POJO
类中实现Serializable
:
public class DetailModel implements Serializable{
String title;
public DetailModel() {
}
public DetailModel(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
在第二个 Activity
中使用此代码获取类:
getIntent().getExtras().getSerializable("mypojo");
//also you can cast extra
DetailModel detailmodel=(Detailmodel) getIntent().getExtras().getSerializable("mypojo");
//if you implemented Parcelable
DetailModel detailmodel=(Detailmodel) getIntent().getExtras().getParcelable("mypojo");
这是第一种方法,另一种更快的方法是使用 Parcelable
,检查这个答案,但你必须在 Parcelable
中做出一些努力:how-to-send-an-object-from-one-android-activity-to-another-using-intent
我建议你使用Parcelable
,也许你需要一些时间来学习它,但你可以在更大的类中感受到速度差异。
此外,如果您的 POJO 中有少量字符串,请尝试使用 intent extras 而不是像那样发送类:
intent.putExtra("model_name",pojo.getName());
//then get
getIntent().getExtras().getString("model_name");
关于android - 如何使用 POJO 类将值从 RecyclerView 传递到另一个 Activity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39307901/