一、添加一个LinearLayout
在android 自定义View学习总结-继承自ViewGroup中,给ViewGroup添加了三个图片,然后实现它的onLayout,然后ViewGroup就能够在滑动中显示出来。然后给VewGroup增加了一个LinearLayout,就是ViewGroup嵌套ViewGroup。
mMyView = (MyView) findViewById(R.id.main_myview);
for(int i=0;i<3;i++){
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource(R.mipmap.ic_launcher);
mMyView.addView(imageView);
}
//这里是新增的LinearLayout
View tView = View.inflate(this,R.layout.test,null);
mMyView.addView(tView);
test.xml布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00"
>
<Button
android:text="这是一个按钮"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
布局文件的效果图,里面有一个Button按钮:
运行结果发现Button不见了!!!!!!!!!!!!!:
二、覆盖onMeasure
其实,实现了ViewGroup的onLayout方法,该方法只计算了它第一层孩子的布局位置,不会给它的孩子的孩子计算,所以,它的孩子的孩子,也就是LinearLayout里面的Button不知道大小,所以也就不能显示。
解决办法就是,覆盖ViewGroup的onMeasure,在里面对子View做测量。这样,LinearLayout里面无论嵌套多深的View,都能正常显示。
测量代码:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
for(int i=0;i<getChildCount();i++){
View childView = this.getChildAt(i);
childView.measure(widthMeasureSpec,heightMeasureSpec);
}
}
三、运行后的结果
可以看到,测量之后,运行的结果就正常了。