gpt4 book ai didi

android - Cardview 位置始终为 -1

转载 作者:行者123 更新时间:2023-11-29 15:42:07 25 4
gpt4 key购买 nike

我正在使用以下代码为 cardview 设置 onClickListener。

@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?

最佳答案

我看到的问题是您在“Oncreateviewholde”中返回了一个新的 View 持有者,而不是您已经创建的 View 持有者。

    @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);
//
// your code

card.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

final int position = holder.getAdapterPosition();
}
});

return new MyViewHolder(itemView); // problem, remove it
return holder; // use this
}

另一件事是,如果您像这样在 holder 构造函数中设置监听器并初始化 View ,这是一个很好的做法

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


public TextView title;
public ImageView image;

public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
image = (ImageView) itemView.findViewById(R.id.thumbnail);
image.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Log.d("pos",""+getAdapterPosition());
removeAt(getAdapterPosition());
}
}
public void removeAt(int position) {
list.remove(position);
notifyDataSetChanged();
}

关于android - Cardview 位置始终为 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38651706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com