我有一个包含图像的ListView,这些图像来自服务器,加载程序然后在ListView的onLoadFinished
setAdapter
下载图像。设置适配器后,我尝试选择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)
为真)。你能建议更优雅的解决方案吗?
答案 0 :(得分:0)
一旦ListAdapter中有一个或多个项目,您是否只能register对{Listinapter DataSetObserver来设置onChange()事件的选择?
答案 1 :(得分:0)
如果您不使用标题,则可以使用ListView
OnHierarchyChangeListener
层次结构更改
private boolean needSelection = true;
public void onChildViewAdded(View parent, View child) {
if (needSelection && indexOfChild(child) == 0) {
trySelectChild(child);
needSelection = false;
}
}