自定义android视图的自定义类型属性

时间:2013-08-20 12:33:23

标签: android android-view

我想创建自定义Android视图( MyCustomView )。在此视图中,我希望拥有自定义类型的属性( MyCustomType )。与此类似:

MyCustomView extends LinearLayout {

    private MyCustomType prop1;

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

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

到目前为止一切顺利。但现在我希望能够从XML设置此属性的值。我可以使用string,int,reference format创建自定义属性,但我不知道如何将此属性定义为 MyCustomType 格式。我想象一下类似的东西:

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

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

谢谢!

2 个答案:

答案 0 :(得分:1)

我真的不明白为什么你需要这个。但您可以使用format =“String”并在布局的属性字段中写入完整的类名。例如:     自定义:为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);

答案 1 :(得分:0)

你不能在android框架中使用自己的属性类型。你可以根据可用类型来拥有自己的 proprties ,但就是这样。不确定在你的情况下你想到了什么类型,但在大多数情况下,无论那个自定义的东西是什么,它都可以通过可用的原语来解决。