在Activity
中,如何访问Expandable ListView
的第一个组视图?
这是我正在做的事情:
public int getFirstVisibleGroup() {
LogUtil.i(TAG, "getFirstVisibleGroup called");
int firstVis = listView.getFirstVisiblePosition();
LogUtil.i(TAG, "firstVis = " + firstVis);
long packedPosition = listView.getExpandableListPosition(firstVis);
LogUtil.i(TAG, "packedPosition = " + packedPosition);
LogUtil.i(TAG, "firstVisibleGroup = " + ExpandableListView.getPackedPositionGroup(packedPosition));
return ExpandableListView.getPackedPositionGroup(packedPosition);
}
public View getGroupView(ExpandableListView listView, int groupPosition) {
LogUtil.i(TAG, "getGroupView called");
int flatPosition = listView.getFlatListPosition(groupPosition);
LogUtil.i(TAG, "flatPosition = " + flatPosition);
int first = getFirstVisibleGroup();
LogUtil.i(TAG, "first = " + first);
LogUtil.i(TAG, "returning child at position " + (flatPosition - first));
return listView.getChildAt(flatPosition - first);
}
我称之为:
View view = getGroupView(listView, 0);
最终它变为listView.getChildAt(0)
。返回的view
为空。
这样做的正确方法是什么?
答案 0 :(得分:1)
所有基于适配器的视图(ListView,GridView,RecyclerView)仅在将视图布置在屏幕上后才将视图添加到自身。这样他们就可以计算出适当的大小并查询足够的子视图。
因此,在onCreate
期间,您永远不会有任何观点。这意味着,如果您想要与其某些子视图进行交互,则必须在以后进行。
一种合适的方法是使用OnPreDraw
侦听器。这是在系统在视图上调用draw(canvas)
之前。例如:
public MyActivity extends Activity implements ViewTreeObserver.OnPreDrawListener {
@Override
public void onCreate(bundle){
... build your layout and your listview
// during onCreate you add a PreDrawListener
rootView.getViewTreeObserver().addOnPreDrawListener(this);
}
@Override
public void onPreDraw() {
... do your logic here !!!
rootView.getViewTreeObserver().removeOnPreDrawListener(this); // remove itself, you only need the fist pass
return true; // must return true, or else the system won't draw anything.
}
}