[英]Android - custom UI with custom attributes
我知道可以创建自定义UI元素(通过View或特定的UI元素扩展)。 但是有可能为新创建的UI元素定义新的属性或属性(我的意思是不是继承的,而是全新的定义了我无法使用默认属性或属性处理的某些特定行为)
例如元素我的自定义元素:
<com.tryout.myCustomElement
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Element..."
android:myCustomValue=<someValue>
/>
那么可以定义MyCustomValue吗?
谢谢
是。 简短指南:
在/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 />
(这里只是一个)。 我从未找到可能类型的完整列表,因此您需要查看一下我猜想的源代码。 我知道的类型是(对另一资源的)引用,颜色,布尔值,维,浮点数,整数和字符串 。 他们很不言自明
除了一个例外,它的工作方式与上述相同。 您的自定义属性需要它自己的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"
/>
非常简单。
修改您的自定义视图的构造函数以解析值。
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()
使用它来相应地更改外观。
在res / values文件夹中,创建attr.xml。 您可以在此处定义属性:
<declare-styleable name="">
<attr name="myCustomValue" format="integer/boolean/whatever" />
</declare-styleable>
然后,当您要在布局文件中使用它时,必须添加
xmlns:customname="http://schemas.android.com/apk/res/your.package.name"
然后您可以将值与customname:myCustomValue=""
是的,您可以。只需使用<resource>
标签。
像这样:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CodeFont" parent="@android:style/TextAppearance.Medium">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#00FF00</item>
<item name="android:typeface">monospace</item>
</style>
</resources>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.