I need to check all element on a ListView to set a label only to a one of those. I can't edit the database or the adapter, I just want to scroll the ListView to perform a check and set a string on a 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("");
}
}
}
How can I do? I need to wait something?
P.S. Obviusly the ListView is not empty.
That seems to be a nasty hack. But okay...
The thing is, that your list won't have children as long as the list is not displayed to the user. But you have to understand that getChildCount
will return the amount of visible list items (so maybe about 10 views) and the position of them will never relate to the actual item position in the adapter.
If you really need to communicate with the views on a such low level you could try to attach a scroll listener to your list:
@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
}
}
来源:https://stackoverflow.com/questions/7699286/getchildcount-returns-0-on-listview