我想创建一个自定义 Android View (MyCustomView)。在此 View 中,我想要一个自定义类型的属性 (MyCustomType)。类似这样:
MyCustomView extends LinearLayout {
private MyCustomType prop1;
public MyCustomType getProp1()
{
return this.prop1;
}
public void setProp1(MyCustomType value)
{
this.prop1 = value;}
}
}
到目前为止一切顺利。但现在我希望能够从 XML 中设置此属性的值。我可以使用字符串、整数、引用格式创建自定义属性,但我看不到如何将此属性定义为 MyCustomType 格式。我想象类似这样的东西:
<declare-styleable name="MyCustomView">
<attr name="prop1" format="MyCustomType"/>
</declare-styleable>
这有可能吗?或者自定义类型属性只能从代码隐藏设置?
谢谢!
最佳答案
我真的不明白你为什么需要这个。但您可以使用 format="String"并在布局的属性字段中写入完整的类名。例如: 自定义:prop1="com.example.MyCustomType"
然后在您的 View 的构造函数中:
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);
关于android - 自定义 Android View 的自定义类型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18335166/