我将数据从我的RecyclerView适配器传递到我的MainActiviy。我还使用适配器中的接口捕获MainActivity的onItemClick()中的CardView项目位置,并使用intent将该位置传递给新的Activity(CardViewDetails)。问题是CardViewDetails加载了错误的CardView。我如何使用CardView"位置"启动正确的CardView?我在这里缺少什么?
MainActivity
...
public void passDataFromAdapter(Bundle bundle) {
data = bundle.getString("spantimeinhours");
data2 = bundle.getLong("timeinhours");
}
// This method works with an interface in the Adapter to capture the
// CardView item position.
@Override
public void onItemClick(int position, final View view) {
Intent intent = new Intent(this,Details.class);
intent.putExtra("adapterSpanTimeInHours",data);
intent.putExtra("adapterTimeInHours",data2);
startActivity(intent);
}
Details
...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Bundle extras = getIntent().getExtras();
msgFromAdapter = extras.getString("adapterSpanTimeInHours");
msg2FromAdapter = extras.getLong("adapterTimeInHours", 0);
}
Adapter
public class MyRecylerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private void passDataFromAdapter(Bundle bundle) {
if (context == null)
return;
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.passDataFromAdapter(bundle); // this method must be implemented inside `MainActivity`
}
}
}
答案 0 :(得分:1)
将其粘贴到onBindViewHolder
中 viewHolder.myView.setOnClickListener(new View.OnClickListener() {
// Handles the row being clicked.
@Override
public void onClick(View view) {
int adapterPos = itemHolder.getAdapterPosition(); // get the item position.
if (adapterPos != RecyclerView.NO_POSITION) {
if (recyclerItemClickListener != null) {
recyclerItemClickListener.onItemClick(adapterPos, itemHolder.itemView);
}
}
}
});