要在Android中添加自定义视图,需要按照以下步骤操作:
- 创建一个新的class继承View或者任何View的子类如
Button
,TextView
,ImageView
等等 - 可以在
attrs.xml
文件中定义自定义属性用在你的视图中 - 重写
onDraw()
方法以绘制自定义视图, 而且你可以重写其他方法比如onMeasure()
和onLayout()
以处理你的视图的度量和布局。 - 在你想要使用自定义视图的布局文件中,添加的你自定义视图的完整名称(如com.sample.widget.CustomView),或者设置它的class属性指定完整的类路径
- 在
Activity
或者Fragment中
通过findViewById()
获取到View
<com.example.widget.CustomView
android:id="@+id/customView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
或者:
<view
class="com.example.widget.CustomView"
id="@+id/customView" />