我有一个ListView,并且在每个ListviewItem中都有一个带有小星星的ImageView(用于将其标记为收藏)。因此,我将OnClickListener放在自定义ArrayAdapter中每个项目的ImageView上。
imgStar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bitmap bitmap = ((BitmapDrawable)imgStar.getDrawable()).getBitmap();
Bitmap bitmap2 = ((BitmapDrawable)(context.getResources().getDrawable(R.drawable.ic_action_not_important))).getBitmap();
if(bitmap != bitmap2) {
imgStar.setImageResource(R.drawable.ic_action_not_important);
} else {
imgStar.setImageResource(R.drawable.ic_action_important);
}
}
});
问题:当我得到一些项目并点击例如第一个项目的星号时,图像会按原样改变,但是图像的一些项目也会更改o.O 我用一些代码对它进行了测试:我不知道的是它只是改变了图像(在下面的另一个项目上),在onclick中执行的代码只针对我真正执行的项目执行点击不是图片也会改变的那个。
为什么列表中随机其他项的图像也会发生变化?我希望有人可以帮助我。
自定义适配器构造代码
public LinkArrayAdapter(Context con, int textViewResourceId) {
super(con, textViewResourceId);
context = con;
}
答案 0 :(得分:1)
主要问题是您无法更改onClick
中的项目图像,然后离开它,并希望它会更新列表中的每个项目。因为onClick
的调用时间与getView
不同。因此,您必须在onClick
之外设置项目图片,但必须在getView
中设置,因此每次getView
调用特定项目时,都会为该项目设置相应的图片。
在CustomAdapter类中定义一个布尔数组:
private boolean[] stars;
然后在类的构造函数方法中,将其初始化为:
this.stars = new boolean[items.size()];
在onClick
方法中:
// **Edited to apply image update at click**
stars[position] = !stars[position];
notifyDataSetInvalidated();
最后在自定义适配器的getView()
方法中
(确保此代码不是在任何其他内部块中):
if (stars[position])
imgStar.setImageResource(R.drawable.ic_action_important);
else
imgStar.setImageResource(R.drawable.ic_action_not_important);
答案 1 :(得分:0)
private int selectedPositions ;
// /... your code.
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
OneComment mComment = mlist.get(position);
mComment.isStart = !mComment.isStart;
if(mComment.isStar){
//set star image
} else{
do not set star image}
}
});
答案 2 :(得分:0)
notifyDataSetInvalidated()
导致List重新加载并转到第一个项目。
请改用notifyDataSetChanged()
。