android - getChildCount() 在 ListView 上返回 0

标签 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("");
        }       
    }
}

我该怎么办?我需要等待吗?

附言显然 ListView 不为空。

最佳答案

这似乎是一个令人讨厌的 hack。不过没关系...

问题是,只要列表不显示给用户,您的列表就不会有子项。 但是您必须了解 getChildCount 将返回可见列表项的数量(因此可能有大约 10 个 View )并且它们的位置永远不会与实际项目位置相关适配器。

如果您真的需要在如此低的级别上与 View 进行通信,您可以尝试将滚动监听器附加到您的列表:

@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
    }
}

关于android - getChildCount() 在 ListView 上返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7699286/

相关文章:

android - 我现在应该删除 .AndroidStudio1.2 文件夹吗

android - Firebase 身份验证有效,但在使用 Google Text to Speech API 时出现错误

android - 密度独立性测试

Android-Firebase onChildChanged

javascript - 使用 javascript : numbers output as octal with missing leading zero HTML 表格输出到 Excel

java - Android TranslateAnimation - 将图像从屏幕右侧移动到屏幕中

javascript - 数据库查询后 jQuery Mobile 刷新 ListView

android - 排序顺序不适用于 listView 和游标加载器

mysql - 从具有零值的单个表返回多列结果

r - 如何用零(0)填充矩阵