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

Way*_*int 111 android custom-controls

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

例如,我的自定义元素:

<com.tryout.myCustomElement
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Element..."
   android:myCustomValue=<someValue>
/>
Run Code Online (Sandbox Code Playgroud)

那么可以定义MyCustomValue吗?

谢谢

小智 255

是.简短指南:

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>
Run Code Online (Sandbox Code Playgroud)

基本上,您必须为<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"
   />
Run Code Online (Sandbox Code Playgroud)

挺直的.

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();
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

distanceExample在此示例中是私有成员变量.TypedArray得到了很多其他东西来解析其他类型的价值观.

就是这样.使用您解析的值View来修改它,例如使用它onDraw()来相应地改变外观.

  • 对于gradle构建,在声明自定义命名空间时应使用`http:// schemas.android.com/apk/res-auto` (22认同)
  • 请注意TypedArray.完成后请务必调用recycle(). (7认同)
  • 在第3步中,您可以简单地使用`String initialText = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","initialText");`其中attr是传入的AttributeSet构造函数和'initialText'是您的自定义属性名称 (2认同)

Mar*_*yer 20

在res/values文件夹中,创建attr.xml.在那里你可以定义你的属性:

<declare-styleable name="">
    <attr name="myCustomValue" format="integer/boolean/whatever" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)

当您想要在布局文件中使用它时,您必须添加

xmlns:customname="http://schemas.android.com/apk/res/your.package.name"
Run Code Online (Sandbox Code Playgroud)

然后你可以使用值 customname:myCustomValue=""