如何从Android中的MainActivity访问onBindViewHolder项目值

时间:2019-12-17 09:24:03

标签: android android-viewholder

我的CarDetailsListAdapter.java文件中有一个如下所示的OnbindViewHolder方法

 @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());

现在我需要从MainActivity访问高于viewHolder.car_amount的值,我不知道如何访问该值

1 个答案:

答案 0 :(得分:1)

您要访问car_amount,但在recyclerview中有多个单元格。我假设您要在单元格上单击“ onClick”后访问它。

在特定单元格上单击时,您可以为适配器提供一个侦听器来呼叫。

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());
   }
}

您的活动:

public CarDetailsListActivity extends Activity implements CarDetailsListListener {
   ...

   mAdapter = new CarDetailsListAdapter(this);

   @Override
   public void onClick(int carAmount){
      ...
   }
}