2012-11-20 22 views
0

我會很感激,如果有人能幫助我一個這樣:)Android是有可能本身就是一個CustomAdapter更新

我有一個自定義適配器(擴展ArrayAdapter),並在其上顯示(movieDatas)的對象,有一個隨時間變化的屬性(downloadProgress)

因爲我在多個地方使用這個適配器,所以我想知道我的CustomAdapter可以偵聽每個movieDatas.downloadProgress屬性,然後更新自己?因此,不使用ArrayAdapter.notifyDataSetChanged 活動,但適配器會自行決定更新。

以前,我每隔5秒就在每個Activity上使用一個Timer,但每次需要調用myListView.invalidate(),但我想知道該適配器是否可以自己處理更改?

非常感謝您的幫助,我從android開發開始。

回答

1

我不知道你是怎麼做的,但它聽起來像你可以完全使用回調來實現它。

1)創建一個像這樣的接口:

public interface OnDownloadProgressChangeListener{ 
    public void onProgress(int progress); 
} 

2)添加到您的MovieData對象:

// We use an ArrayList because you could need to listen to more than one event. If you are totally sure you won't need more than one listener, just change this with one listener 
private ArrayList<OnDownloadProgressChangeListener> listeners = new ArrayList<OnDownloadProgressChangeListener>(); 

public void addDownloadProgressChangeListener(OnDownloadProgressChangeListener listener){ 
    listeners.add(listener); 
} 

public void clearDownloadProgerssChangeListeners(){ 
    listeners.clear(); 
} 

//Add any handlers you need for your listener array. 


// ALWAYS use this method to change progress value. 
public void modifyProgress(int howMuch){ 
    progress+=howMuch; 
    for (OnDownloadProgressChangeListener listener : listeners) 
      listener.onProgress(progress); 
} 

3)覆蓋您的自定義適配器add方法

@Override 
public void add(final MovieData item){ 
    item.addDownloadProgressChangeListener(new OnDownloadProgressChangeListener(){ 
     public void onProgress(final int progress){ 
      // Add your logic here 
      if (progress == 100){ 
        item.update(); 
      } 
     } 
    }); 
    super.add(item); 
} 

4)每當物品被修改時,請在您的適配器上撥打notifyDataSetChanged()。您甚至可以將其添加到add實現中的super.add(item)行之後,但如果您要添加大量項目,則效率極低:先添加它們,然後通知更改。

+0

編輯,忘記調用super.add(item)添加重寫的方法。 – razielsarafan

相關問題