android 自定义view之 TypeArray
时间: 2023-07-28 17:12:01 浏览: 81
TypeArray 是 Android 中的一个特殊的资源类型,用于在 XML 中声明自定义 View 的属性。使用 TypeArray 可以方便地在 XML 布局中指定 View 的属性,而不需要在 Java 代码中进行硬编码。
使用 TypeArray 的步骤如下:
1. 在 res/values/attrs.xml 文件中定义自定义 View 的属性。
```xml
<resources>
<declare-styleable name="MyCustomView">
<attr name="customAttr1" format="integer" />
<attr name="customAttr2" format="string" />
<attr name="customAttr3" format="boolean" />
</declare-styleable>
</resources>
```
2. 在自定义 View 的构造函数中获取 TypedArray 对象,并从中获取属性值。
```java
public class MyCustomView extends View {
private int customAttr1;
private String customAttr2;
private boolean customAttr3;
public MyCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
customAttr1 = a.getInt(R.styleable.MyCustomView_customAttr1, 0);
customAttr2 = a.getString(R.styleable.MyCustomView_customAttr2);
customAttr3 = a.getBoolean(R.styleable.MyCustomView_customAttr3, false);
a.recycle();
}
}
```
在上面的代码中,`context.obtainStyledAttributes(attrs, R.styleable.MyCustomView)` 用于获取 TypedArray 对象,`R.styleable.MyCustomView` 是在 attrs.xml 文件中定义的自定义属性集合,`a.getInt()`、`a.getString()`、`a.getBoolean()` 用于从 TypedArray 对象中获取属性值,最后需要调用 `a.recycle()` 来回收 TypedArray 对象。
3. 在 XML 布局中使用自定义 View,并设置属性值。
```xml
<com.example.MyCustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:customAttr1="123"
app:customAttr2="hello"
app:customAttr3="true" />
```
在上面的代码中,`app:customAttr1`、`app:customAttr2`、`app:customAttr3` 是在 attrs.xml 文件中定义的自定义属性名,可以在 XML 布局中使用。