之前写自定义ViewGroup的时候,一般都像下面:
public class TestView extends RelativeLayout {
public TestView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
LayoutInflater.from(context).inflate(R.layout.merge_test, this, true);
}
}
merge_test.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/b1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/b2"
android:text="aaa" />
<Button
android:id="@+id/b2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="bbb" />
</RelativeLayout>
这样实际上是有性能问题的,会产生一个RelativeLayout(TestView本身)套嵌另一个RelativeLayout(xml)的现象。
还有另外一个问题,如果使用TestView的measure、layout、draw等方法(不是onXXX),实际上只是直接作用在其子View(xml的RelativeLayout)上,可能有潜在问题。
合理的方法是将xml里的RelativeLayout改为merge。merge不会检查根View的attr,比如android:layout_below等等,所有东西完全可用。但是根View(TestView)本身的一些参数,要自己调用函数设置(比如,LinearLayout的Orientation)。
这样可以减少一层ViewGroup,还可以减少想当然的调用问题。