我有一个包含图像的 ListView,这些图像来自服务器,加载程序下载图像然后在onLoadFinished
ListViewsetAdapter
中。设置适配器后,我尝试选择 ListView 的第一项,但它没有效果。我怀疑 ListView 还没有准备好选择,所以我设法通过一种奇怪的方式来做到这一点,比如覆盖 setSelection 函数:
public void setSelection(final int position) {
// TODO Auto-generated method stub
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
Log.i(TAG, "thread runned.");
boolean is_view_created = false;
while (!is_view_created) {
try {
Thread.sleep(100);
getListView();
if (getListView().getChildAt(position) != null)
is_view_created = true;
else {
Log.i(TAG, "Waiting for the list view to initialize.");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
Log.i(TAG, "Waiting for the list view to initialize.");
}
}
MiddleMenuListFragment.super.setSelection(position);
View initial_selection_view = getListView().getChildAt(position);
initial_selection_view.performClick();
((MiddleMenuListAdapter)getListAdapter()).light_me_up = position;
getActivity().runOnUiThread(new Runnable(){
@Override
public void run() {
((MiddleMenuListAdapter)getListAdapter()).notifyDataSetChanged();
}
});
}
}, 400);
}
但是这种方法并不是很安全。它有时会进入循环(无法getListView().getChildAt(position != null)
实现)。你能建议更优雅的解决方案吗?