RecyclerView.onBindViewHolder不会填充所有项目

时间:2018-12-16 21:28:42

标签: android android-recyclerview

问题出在onBindViewHolder上,我试图根据条件设置按钮的文本。

无论我尝试什么,似乎只评估了第一个if语句(else-if或else的任何一个),而我仅获得与其匹配的按钮,所有其他按钮文本均设置为null

这是我自定义的RecyclerViewAdapter

public class ParallelRecyclerViewAdapter
    extends RecyclerView.Adapter<ParallelRecyclerViewAdapter.ParallelViewHolder> {

  private int listItemLayout;
  private ArrayList<ParallelClusterItem> itemListForAdapter;

  public ParallelRecyclerViewAdapter(int layoutId, ArrayList<ParallelClusterItem> inputList) {
    listItemLayout = layoutId;
    itemListForAdapter = inputList;
  }

  @NonNull
  @Override
  public ParallelViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(listItemLayout, parent, false);
    return new ParallelViewHolder(view);
  }

  @Override
  public void onBindViewHolder(@NonNull ParallelViewHolder holder, int position) {
    Button button = holder.year;

    String oldPhotoYear = itemListForAdapter.get(position).getmOldPhotoYear();
    String relativeYearFrom = itemListForAdapter.get(position).getmRelativeYearFrom();

    if (oldPhotoYear != null) {
      button.setText(oldPhotoYear);
    } else if (relativeYearFrom != null) {
      button.setText(relativeYearFrom);
    } else {
      button.setText("unknown");
    }
  }

  @Override
  public int getItemCount() {
    return itemListForAdapter == null ? 0 : itemListForAdapter.size();
  }

  public class ParallelViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    Button year;

    ParallelViewHolder(View itemView) {
      super(itemView);
      year = itemView.findViewById(R.id.row_item);
      year.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
      int pos = getAdapterPosition();
      ParallelClusterItem item = itemListForAdapter.get(pos);

      Intent intent = new Intent(ParallelMapFragmentActivity.instance, ImageSliderActivity.class);
      intent.putExtra("path", item.getPath());

      ParallelMapFragmentActivity.instance.startActivity(intent);
    }
  }
}

0 个答案:

没有答案