使用以下代碼爲cardview設置onClickListener。Cardview position is always -1
@Override
public MyViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.album_card, parent, false);
final CardView card = (CardView)itemView.findViewById(R.id.card_view);
final MyViewHolder holder = new MyViewHolder(itemView);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
StateListAnimator stateListAnimator = AnimatorInflater
.loadStateListAnimator(mContext, R.anim.lift_on_touch);
card.setStateListAnimator(stateListAnimator);
}
card.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final int position = holder.getAdapterPosition();
Log.d("Position",""+position);
if (position == 2) {
Intent intent = new Intent(mContext, ExperienceActivity.class);
mContext.startActivity(intent);
}
}
});
return new MyViewHolder(itemView);
}
OnClickListener工作正常,但爲什麼該位置總是返回-1?
holder.getAdapterPosition()您正在調用。但是,你在哪裏設置持有人的位置? –
林不知道。你應該在哪裏設置它..你可以澄清 – Learner
最終CardView卡=(CardView)itemView.findViewById(R.id.card_view); final MyViewHolder holder = new MyViewHolder(itemView); holder.setPosition(YOUR_POSITION); –