Android: Custom View和include标签的区别

时间:2022-01-30 21:02:28

Custom View, 使用的时候是这样的:

    <com.example.home.alltest.view.MyCustomView
android:id="@+id/customView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.example.home.alltest.view.MyCustomView>

使用的时候是这样的:

_customView = (MyCustomView)findViewById(R.id.customView1);
_customView.setText("What's", "UP?");

但是include是一个表情,在布局中使用的时候是这样的:

<include layout="@layout/view_my_custom"
android:id="@+id/customView1" />

这个表情将会被layout属性制定的布局文件替换掉,所以这里的include只是view_my_custom布局文件的RelativeLayout占位符。

在代码中使用的时候是这样的:

RelativeLayout _relativeLayout = (RelativeLayout)findViewById(R.id.customView1);
TextView textWorld = (TextView)_relativeLayout.findViewById(R.id.txtWorld);

区别就是,第一种方法可以直接findViewById之后当做你的自定义类来使用。而include标签只是占位符,在编译的时候这里就变成了你的自定义空间的那一堆各种Layout了。所以在使用的时候只能在脑中把被替换掉的layout文件再补回来。