Android - 具有自定义属性的自定义UI

时间:2011-09-30 09:30:40

标签: android custom-controls

我知道可以创建自定义UI元素(通过View或特定的UI元素扩展)。但是有可能为新创建的UI元素定义新的属性或属性(我的意思是不是继承的,而是全新的定义一些我无法用默认属性或属性处理的特定行为)

e.g。 element我的自定义元素:

<com.tryout.myCustomElement
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Element..."
   android:myCustomValue=<someValue>
/>

那么可以定义 MyCustomValue 吗?

THX

3 个答案:

答案 0 :(得分:249)

是。简短指南:

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()中使用它来相应地更改外观。

答案 1 :(得分:19)

在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=""

一起使用

答案 2 :(得分:-11)

是的,你可以。只需使用<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>

link from official website

相关问题