是的。简短指南:
1。创建属性 XML
在/res/values/attrs.xml 中创建一个新的 XML 文件,包含属性和类型
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<declare-styleable name="MyCustomElement">
<attr name="distanceExample" format="dimension"/>
</declare-styleable>
</resources>
基本上,您必须为包含所有自定义属性的视图设置一个<declare-styleable />(这里只有一个)。我从未找到可能类型的完整列表,因此您需要查看我猜想的来源。我知道的类型是引用(对另一个资源)、颜色、布尔值、维度、浮点数、整数和字符串。它们是不言自明的
2。在布局中使用属性
它的工作方式与您在上面所做的相同,但有一个例外。您的自定义属性需要它自己的 XML 命名空间。
<com.example.yourpackage.MyCustomElement
xmlns:customNS="http://schemas.android.com/apk/res/com.example.yourpackage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Element..."
customNS:distanceExample="12dp"
/>
非常直接。
3。利用你传递的值
修改自定义视图的构造函数以解析值。
public MyCustomElement(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCustomElement, 0, 0);
try {
distanceExample = ta.getDimension(R.styleable.MyCustomElement_distanceExample, 100.0f);
} finally {
ta.recycle();
}
// ...
}
distanceExample 在此示例中是私有成员变量。 TypedArray 有很多其他的东西来解析其他类型的值。
就是这样。使用 View 中的解析值来修改它,例如在onDraw() 中使用它来相应地改变外观。