问题
I have an OnbindViewHolder method in my CarDetailsListAdapter.java
file like below
@Override
public void onBindViewHolder(final CarDetailsListAdapter.ViewHolder viewHolder, final int i) {
final CarDetailModel currentItem = getItem(i);
Log.e("check", String.valueOf(modelItems));
Log.e("check position", i+" "+currentItem.getCarIsSelected());
// check car min is no cabs or not
if(!currentItem.getCarMin().equals("No cabs")) {
if (selectcar) {
viewHolder.itemView.setSelected(true);
//selectedItem =viewHolder.getLayoutPosition();
selectcar = false;
} else {
viewHolder.itemView.setSelected(false);
}
}
// set default select car
viewHolder.itemView.setSelected(selectedItem == i);
if(first&¤tItem.getCarIsSelected())
{
viewHolder.itemView.setSelected(true);
first=false;
}
viewHolder.car_min.setText(currentItem.getCarMin());
viewHolder.car_amount.setText(currentItem.getCarAmount());
Now I need to access above viewHolder.car_amount
value from my MainActivity, i have no idea how to access this value
回答1:
You want to access car_amount but you have multiple cell in your recyclerview. I will suppose that you want to access it after an "onClick" on your cell.
You can give to your adapter a listener to call when a click is done on a specific cell.
public CarDetailsListAdapter(CarDetailsListListener listener){
mListener = listener;
}
@Override
public void onBindViewHolder(final CarDetailsListAdapter.ViewHolder viewHolder, final int i) {
viewHolder.itemView.setOnClickListener(v->{
mListener.onClick(currentItem.getCarAmount());
}
}
Your activity :
public CarDetailsListActivity extends Activity implements CarDetailsListListener {
...
mAdapter = new CarDetailsListAdapter(this);
@Override
public void onClick(int carAmount){
...
}
}
来源:https://stackoverflow.com/questions/59371098/how-to-access-an-onbindviewholder-item-value-from-mainactivity-in-android