如何知道何时完成Android ListView的填充

mah*_*eng 13 events android listview populate

我有一个包含ListView的子Activity.此活动是从SQLite游标异步填充的.列表项包含TextView,RadioButton和普通Button.XML如下所示:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/rlCategoryListItemLayout" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content">
 <TextView android:id="@+id/tvCategoryListItemTitle" style="@style/uwLargeListItemLabelStyle" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:singleLine="true" android:text="This is a test note title" />
 <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:gravity="center_vertical">
  <RadioButton android:id="@+id/rdoCategoryListItemSelect" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginRight="10dip" />
  <Button android:id="@+id/btnCategoryListItemDelete" android:background="@drawable/delete_red" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" />
 </LinearLayout>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

我必须做一些逻辑来确定默认选择哪个RadioButton,并且在ListView已经加载之前我不能这样做.问题是,到目前为止我尝试过的所有事件(onCreate,onPostCreate,onResume,onWindowFocusChanged),ListView子计数为零.我也尝试在ArrayAdapter类中使用getView方法,但该方法被称为多个时间,并且ListView子计数每次都可能不同,从而导致意外结果.显然,这些事件在ListView完成填充其子项之前触发.

是否有我可以侦听的事件,或者其他一些方法来确定ListView何时完成填充并且可以通过编程方式修改其所有子代?

谢谢!

Ren*_*vol 6

您可以使用Handler来完成此任务,如下所示:

在您的活动中,将Handler添加为任何其他属性.

private Handler mListViewDidLoadHanlder = new Handler(new Handler.Callback() { 
    @Override
    public boolean handleMessage(Message message) {
        //Do whatever you need here the listview is loaded
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)

在listview适配器的getView方法中,你进行比较以查看当前位置是否是最后一个位置,因此,它将完成(只需将它放在返回之前):

public View getView(int position, View convertView, ViewGroup parent) {
         //Your views logic here

         if (position == mObjects.size() - 1) {
                mViewDidLoadHanlder.sendEmptyMessage(0);
            }

         return convertView;
     }
Run Code Online (Sandbox Code Playgroud)

  • 数据大小(mObjects)与getView中显示的实际数字无关. (4认同)

Eri*_*ine 1

ListView 实际上并不为它正在呈现的数据列表中的每个元素创建视图。相反,它会回收视图以便响应而不占用内存。当您说需要填充 ListView 时,您可能会重新考虑您真正需要什么。

如果您更详细地了解您的应用程序并发布一些代码,可能会有所帮助。