getChildCount()在ListView上返回0

JoP*_*JoP 2 android listview zero

我需要检查ListView上的所有元素,只将标签设置为其中一个.我无法编辑数据库或适配器,我只想滚动ListView以执行检查并在TextView上设置字符串.

@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("");
        }       
    }
}
Run Code Online (Sandbox Code Playgroud)

我能怎么做?我需要等一下吗?

PS Obviusly ListView不为空.

Kni*_*edi 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
    }
}
Run Code Online (Sandbox Code Playgroud)