gpt4 book ai didi

android - 获取第一组Expandable ListView的View句柄

转载 作者:行者123 更新时间:2023-11-30 01:19:47 26 4
gpt4 key购买 nike

Activity 中,如何访问 Expandable ListView 的第一个组 View ?

这是我正在做的:

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 为 null。

正确的做法是什么?

最佳答案

所有基于适配器的 View (ListView、GridView、RecyclerView)仅在 View 布局到屏幕后才将 View 添加到自身。这样他们就可以计算出适当的大小并查询足够的 subview 。

因此,在 onCreate 期间,您将永远不会有任何 View 。这意味着如果您想与其某些 subview 进行交互,则必须稍后发生。

一种合适的方法是使用OnPreDraw 监听器。那是在系统调用 View 上的 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.
}

}

关于android - 获取第一组Expandable ListView的View句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37279497/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com