1

当我单击列表视图的单个项目时,我正在尝试刷新列表视图。例如,我正在尝试做这样的事情:

public class RssItemsAdapter extends ArrayAdapter<Item> {
private TextView txtTitle;
private ImageView imgFavourite;
private int resourceId;
private Context context;
private List<Item> items = new ArrayList<Item>();

public RssItemsAdapter(Context context, int resourceId, List<Item> items)
{
    super(context, resourceId, items);
    this.context = context;
    this.items = items;
    this.resourceId = resourceId;
}

@Override
public int getCount() {
    return items.size();
}

@Override
public Item getItem(int index) {
    return items.get(index);
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    View row = convertView;
    Item item = getItem(position);      

    if (row == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(resourceId, parent, false);
    }

    txtTitle = (TextView) row.findViewById(R.id.title);
    txtTitle.setText(item.getTitle());

    imgFavourite = (ImageView) row.findViewById(R.id.favourite);
    imgFavourite.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (item.isFavourite() == true) {
                imgFavourite.setBackgroundResource(android.R.drawable.btn_star_big_off);
            }
            else {
                imgFavourite.setBackgroundResource(android.R.drawable.btn_star_big_on);
            }
        }
    });

    // add a "star" icon on favourite items
    if (item.isFavourite() == true)
        imgFavourite.setBackgroundResource(android.R.drawable.btn_star_big_on);
    else
        imgFavourite.setBackgroundResource(android.R.drawable.btn_star_big_off);


    return row;
}

每次我单击imgFavourite图标时,它都应该改变。问题出在哪里?

4

1 回答 1

0

看起来您从未更改 item.isFavourite() 的值。假设您想在单击该项目时切换...

imgFavourite.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {

        // Toggle the current state
        item.setIsFavourite(!item.isFavourite());

        if (item.isFavourite() == true) {
            imgFavourite.setBackgroundResource(android.R.drawable.btn_star_big_off);
        }
        else {
            imgFavourite.setBackgroundResource(android.R.drawable.btn_star_big_on);
        }
    }
});

此外,您应该在 ListView 的 onItemClickListsner 中进行此类工作。照原样,这将在每次看到新行时创建一个新的 onClickListener。除此之外,检查“视图持有者模式”。

于 2012-10-18T22:12:51.673 回答