1

我想创建一个自定义 Android 视图(MyCustomView)。在这个视图中,我想要一个自定义类型(MyCustomType)的属性。与此类似:

MyCustomView extends LinearLayout {

    private MyCustomType prop1;

    public MyCustomType getProp1()
    {
        return this.prop1;
    }

    public void setProp1(MyCustomType value)
    {
        this.prop1 = value;}
    }
}

到目前为止,一切都很好。但现在我希望能够从 XML 设置此属性的值。我可以使用字符串、int、引用格式创建自定义属性,但我看不到如何将此属性定义为MyCustomType格式。我想像这样的东西:

<declare-styleable name="MyCustomView">
    <attr name="prop1" format="MyCustomType"/>
</declare-styleable>

这有可能吗?或者自定义类型属性只能从后面的代码中设置?

谢谢!

4

2 回答 2

1

我真的不明白你为什么需要这个。但您可以使用 format="String" 并在布局的属性字段中写入完整的类名。例如:custom:prop1="com.example.MyCustomType"

然后在您的视图的构造函数中:

TypedArray a = context.getTheme().obtainStyledAttributes(
    attrs,
    R.styleable.MyCustomView,
    0, 0);
String className = a.getString(R.id.prop1);
Class<MySustomType> c = Class.forName(className);
MySustomType prop = c.newInstance();
setProp1(prop);
于 2013-08-20T13:17:28.597 回答
0

您不能在 android 框架中使用自己的属性类型。您可以根据可用类型使用自己的属性,仅此而已。不确定您的情况是什么类型,但在大多数情况下,无论自定义的东西是什么,它都可以通过可用的原语来解决。

于 2013-08-20T13:20:12.437 回答