如何使最后一个列表项与android中的其他列表项不同?

时间:2016-08-05 20:44:01

标签: android xml android-recyclerview

我有一个recyclerview和一个适配器:

public class PaymentMethodAdapter extends RecyclerView.Adapter<PaymentMethodAdapter.ViewHolder> {

    private List<PaymentMethod> mPaymentMethods = new ArrayList<>(0);

    public PaymentMethodAdapter(List<PaymentMethod> paymentMethods) {
        mPaymentMethods = paymentMethods;
        int size = mPaymentMethods.size();
        mPaymentMethods.add(size + 1, null);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_payment_method_list, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (mPaymentMethods.get(position) == null) {  // Last item
            // Display add payment method item.

        }
    }

    @Override
    public int getItemCount() {
        return mPaymentMethods.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.item_payment_method_image_view) ImageView paymentImageView;
        @Bind(R.id.item_payment_method_card_number_text_view) TextView cardNumberTextView;
        @Bind(R.id.item_current_payment_method_image_view) ImageView currentMethodImageView;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}

我想这样做,以便当到达mPaymentMethods中的最后一个元素时,使用不同的列表项布局。基本上我想自定义列表中的最后一项。

如何自定义列表中的最后一项使用与同一列表中其他项不同的布局?

谢谢。

1 个答案:

答案 0 :(得分:3)

您应该如下覆盖getItemViewType。

@Override
public int getItemViewType(int position) {
    return position == mPaymentMethods.size() - 1 ? 1 : 0;
}

根据视图类型

启动视图
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
   View view;
   if(viewType == 0){
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_payment_method_list_0, parent, false);
        return new ViewHolder0(view);
   } else {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_payment_method_list_1, parent, false);
        return new ViewHolder1(view);
   }

}

最后使用所选择的布局

 @Override
 public void onBindViewHolder(ViewHolder holder, int position) {
   if (holder instanceOf ViewHolder0){
      //do stuff with layout 0
   } else {
      // do stuff with layout 1
   }        
 }