我知道可以创建自定义UI元素(通过视图或特定的UI元素扩展)。但是,是否可以为新创建的UI元素定义新的属性或属性(我的意思是不是继承的,而是全新的,以定义一些我无法使用默认属性或属性处理的特定行为)
例如,元素我的自定义元素:
<com.tryout.myCustomElement
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Element..."
android:myCustomValue=<someValue>
/>
那么是否可以定义MyCustomValue呢?
Thx
发布于 2011-09-30 17:57:02
是。简短指南:
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()
中使用它来相应地更改外观。
发布于 2011-09-30 17:55:32
在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=""
一起使用
发布于 2011-09-30 17:42:18
是的,你使用<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>
https://stackoverflow.com/questions/7608464
复制相似问题