1

I'm trying to refresh the list view when I click on a single item of the list view. For example I'm trying to do something like this:

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;
}

Every time I click on the imgFavourite icon it should change. Where is the problem?

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 に答える