在回收者视图中从单击的项目中获取价值

时间:2019-03-05 18:08:07

标签: android android-recyclerview android-viewholder

我有一个物品清单。这些数据是从API接收的,然后通过回收视图列出。现在是这样的:https://imgur.com/a/h4mYXD6

当我在这些项目之一上按下心脏时,我想从该特定项目中接收数据。我不确定该怎么做。现在,我已经为心脏图标创建了一个侦听器,但是现在我陷入了困境。我想获取包含名称,pictureURL和到期日期的数据。

我有一个适配器,在其中将数据与视图绑定。这是onCreateViewHolder:

@Override
public FoodViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    //inflating and returning our view holder
    LayoutInflater inflater = LayoutInflater.from(mCtx);
    View view = inflater.inflate(R.layout.layout_food, parent, false);
    return new FoodViewHolder(view);
}

这是我的OnBindViewHolder方法:

@Override
public void onBindViewHolder(FoodViewHolder holder, int position) {
    //getting the product of the specified position
    Food food = foodList.get(position);

    holder.heart.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v){
            switch (v.getId()) {
                case R.id.heart:
//what code do i write here???
break;
            }
        }
    });

这是正确的方法吗?我从这里去哪里?

3 个答案:

答案 0 :(得分:0)

要在侦听器中获取项目,可以使用ViewHolder的getAdapterPosition

Food clickedFood = foodList.get(holder.getAdapterPosition());

有关更多信息,请参见文档:https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html#getAdapterPosition()

然后,您可以访问clickedFood的字段和方法来获取特定的数据派。

答案 1 :(得分:0)

创建一个接口以将数据发送到活动 在适配器类中:

private FoodListener foodListener;

public void setClickItemListener(FoodListener foodListener) {
    this.foodListener= foodListener;
}
public interface FoodListener {
    void onHeartClick(Food food);
}


@Override
public void onBindViewHolder(FoodViewHolder holder, int position) {
      //getting the product of the specified position
      final Food food = foodList.get(position);

      holder.heart.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v){
        switch (v.getId()) {
            case R.id.heart:
                foodListener.onHeartClick(food);
        }
     }
});

活动中的实施界面:

public class MainActivity implements Adapter.FoodListener {
    @Override
    onCreate(...) {
          .....
          recyclerViewAdapter.setListener(this);
    }
    @Override
    void onHeartClick(Food food) {
         //Get food here
    }
}

答案 2 :(得分:0)

您需要像这样在OnCreateViewHolder方法中的视图上设置单击侦听器,并将数据传递给接口方法,以便您可以更新Activity。希望这会有所帮助。

 @Override
public FoodViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    //inflating and returning our view holder
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.layout_food, parent, false);
     FoodViewHolder holder = new FoodViewHolder(view);
    holder.heartView.setOnClickListener { v-> 
              Food food = list.get(holder.getAdapterPosition());
        foodListener.OnClick(food);
    }
    return holder;
}