先在viewGroup里面定义一个方法,用于获取放在viewGroup中的listview
private void getListView() {
int childs = this.getChildCount();
if (childs > 0) {
for (int i = 0; i < childs; i++) {
View childView = getChildAt(i);
if (childView instanceof ListView) {
mListView = (ListView) childView;
}
}
}
}
int childs = this.getChildCount();
if (childs > 0) {
for (int i = 0; i < childs; i++) {
View childView = getChildAt(i);
if (childView instanceof ListView) {
mListView = (ListView) childView;
}
}
}
}
解释一下这段代码:
首先获取viewGroup子view的数量,然后根据数量判断是否有子view,如果有,则遍历子view获取其中class为ListView(可以是你任意想要获取view的类,前提是你已经把该view放到viewGroup中)的子view。
接下来很重要!!!
我们这个方法是放在viewGroup的类里面的,但要在viewGroup的什么地方走这个方法呢?我试过放到构造方法里面,例如:
public MyPtrRefresh_LoadView(Context context, AttributeSet attrs) {
super(context, attrs, 0);
this.context = context;
getListView();
}
super(context, attrs, 0);
this.context = context;
getListView();
}
这是将代码放到viewGroup的第二个构造方法中执行,经测试发现完全获取不到listView。经过一番百度google之后,我发现需要将方法放到viewGroup重写的onLayout方法里面运行,就能获取listview
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
// 初始化ListView对象
if (mListView == null) {
getListView();
}
}
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
// 初始化ListView对象
if (mListView == null) {
getListView();
}
}
onLayout方法是ViewGroup中子View的布局方法,用于放置子View的位置。放置子View很简单,只需在重写onLayout方法,然后获取子View的实例,调用 子View的layout方法实现布局。在实际开发中,一般要配合onMeasure测量方法一起使用。