2012-10-18 132 views
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圖標應該改變。哪裏有問題?

+0

使用listView的notifyDateSetChange()方法 – Houcine

回答

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。除此之外,請檢查「查看持有者模式」。

+0

如何在ListView的onItemClickListener中做這項工作?我的意思是我怎樣才能訪問listView childs? – fmp

+0

您將在該回調中獲得項目位置,然後您可以使用它調用ListView.getItemAtPosition(position)。如果您需要操作它,也會給您點擊的視圖。 我現在意識到你可能只想讓imgFavourite可點擊。如果是這樣的話,那麼忘記我說的onItemClicked(...),因爲這將適用於整行。 –