2011-10-08 80 views
2

我需要檢查ListView上的所有元素以將標籤僅設置爲其中的一個。 我無法編輯數據庫或適配器,我只想滾動ListView來執行檢查並在TextView上設置一個字符串。getChildCount()在ListView上返回0

@Override 
protected void onResume(){ 
    super.onResume(); 
    ... 
    cursor = getCursor(); 
    startManagingCursor(cursor); 
    adapter = new SimpleCursorAdapter(this,R.layout.profile_item_layout,cursor,from,to); 
    lst_profiles.setAdapter(adapter); 
    SharedPreferences customSharedPreference = PreferenceManager.getDefaultSharedPreferences(ProfilerActivity.this.getApplicationContext()); 
    long current = customSharedPreference.getLong(ProfileManager.CURRENT, -1); 
    toast(lst_profiles.getChildCount()); //display 0 
    if(current!=-1){ 
     for(int i=0;i<lst_profiles.getChildCount();i++){ 
      if(lst_profiles.getItemIdAtPosition(i)==current) 
       ((TextView)lst_profiles.getChildAt(i).findViewById(R.id.activeLabel)).setText(getString(R.string.active)); 
      else 
       ((TextView)lst_profiles.getChildAt(i).findViewById(R.id.activeLabel)).setText(""); 
     }  
    } 
} 

我該怎麼辦?我需要等一下嗎?

P.S.顯然ListView不是空的。

+0

你是如何()調用這裏getCursor?我沒有看到一個活動或上下文的方法... – Maximus

+0

是的我在onResume()中調用getCursor()。該應用程序工作正常,唯一的問題是getChildCount() – JoP

回答

10

這似乎是一個討厭的黑客。但沒關係......

事情是,只要列表不顯示給用戶,您的列表將不會有子項。 但是你必須明白,getChildCount將返回可見列表項的數量(所以可能大約10個視圖),它們的位置將永遠不會與適配器中的實際項目位置相關。

如果你真的需要在這樣低的水平的意見進行溝通,你可以嘗試滾動監聽器連接到您的列表:

@Override 
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { 
    for (int i = 0; i < visibleItemCount; i++) { 
     View child = getChildAt(i); 
     // i + firstVisibleItem == the actual item position in the adapter 
    } 
} 
+1

呵呵,[這裏](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235# 5235),您可以找到所需的所有信息,瞭解如何,何時以及何時接受答案。 – Knickedi