自定义View与merge节点

之前写自定义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,还可以减少想当然的调用问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值