How to Access an onBindViewHolder item Value from MainActivity in Android

一世执手 提交于 2020-02-06 08:43:25

问题


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&&currentItem.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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!