一、简述
在XML中向ViewGroup中添加组件,这个问题貌似很简单,但是只有在简单中才会发现不简单,其实好多复杂的东西都是由简单的东西一步一步演化而来的,这是道家所谓的一生二、二生三、三生万物,以后我们还将通过剖析一个布局类来更深入的了解ViewGroup,不过那是后话了,呵呵。
那么我们可以通过怎样的方式来添加了。请看:
<com.iaiai.HelloViewGroup android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="iaiai继承ViewGroup研究"/> </com.iaiai.HelloViewGroup>
貌似这个方法可以先ViewGroup中加入组件,但是,实际上我们运行后会发现,其实这个组件是不会显示的。
有兴趣的读者可以运行试试。效果是下面这样的。
二、为啥不显示
那么为啥这个ViewGroup里面的TextView没有显示呢,我也为这个问题困扰过很久,其实,有时候我们不是学不会,而是不会学,知识千万遍,方法有多少。那到底要怎样做呢?
其实很简单,我们只需要在ViewGroup中的onMeasure方法里添加一个对子元素的遍历,并且在onLayout中添加一个布局遍历就实现了简单的布局了。
下面给出代码:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub super.onMeasure(widthMeasureSpec, heightMeasureSpec); int childCount = getChildCount(); for(int i = 0; i < childCount; i ++){ View v = getChildAt(i); v.measure(widthMeasureSpec, heightMeasureSpec); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int childCount = getChildCount(); for(int i = 0; i < childCount; i ++){ View v = getChildAt(i); v.layout(l, t, r, b); } }
运行效果: