填充recyclerview并选择第一项

时间:2017-02-07 13:00:48

标签: android android-recyclerview

我有一个RecyclerView,其中填充了API获取的列表。如何在不单击的情况下将列表中的第一个项目设为默认选择?我还需要在我的片段中将所选项目作为对象,我使用RecyclerView。这是我的RecyclerView

    public class PaymentMethodAdapter extends RecyclerView.Adapter<PaymentMethodAdapter.PaymentTermsViewHolder> {
    Context mContext;
    List<PaymentInfo> mPaymentInfoList;
    OnItemInteractionListener mListener;
    PreferenceAdapter mPreferenceAdapter;
    int selectedPosition = -1;

    public interface OnItemInteractionListener {
        void onClick(PaymentInfo paymentInfo);
    }

    public PaymentMethodAdapter(Context context, List<PaymentInfo> paymentInfoList) {
        this.mContext = context;
        this.mPaymentInfoList = paymentInfoList;
        this.mPreferenceAdapter = new PreferenceAdapter(mContext);
    }

    @Override
    public PaymentTermsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        ItemPaymentInfoBinding mBinder = ItemPaymentInfoBinding.inflate(layoutInflater, parent, false);
        return new PaymentTermsViewHolder(mBinder);
    }

    @Override
    public void onBindViewHolder(final PaymentTermsViewHolder holder, int position) {
        PaymentInfo paymentInfo = mPaymentInfoList.get(position);
        holder.bind(paymentInfo);
        if (selectedPosition == position) {
            holder.mBinder.imageView.setImageResource(R.drawable.ok_48);
            mListener.onClick(paymentInfo);
        } else {
            holder.mBinder.imageView.setImageResource(R.drawable.ok_50);
        }

        holder.mBinder.rlPaymentHolder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notifyItemChanged(selectedPosition);
                selectedPosition = holder.getLayoutPosition();
                notifyItemChanged(selectedPosition);
            }
        });
    }

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

    public static class PaymentTermsViewHolder extends RecyclerView.ViewHolder {
        ItemPaymentInfoBinding mBinder;

        public PaymentTermsViewHolder(ItemPaymentInfoBinding binder) {
            super(binder.getRoot());
            this.mBinder = binder;
        }

        public void bind(PaymentInfo paymentInfo) {
            mBinder.setPaymentInfo(paymentInfo);
            mBinder.executePendingBindings();
        }
    }

    public void addOnItemInteractionListener(OnItemInteractionListener listener) {
        this.mListener = listener;
    }

    public void removeInteractionListener() {
        mListener = null;
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用performClick()函数将此项用于项目或按钮的功能在条件成立时单击自身。 例如:

    if(positon == 0)
    holder.itemView.performClick();