android - 自定义 Android View 的自定义类型属性

标签 android android-view

我想创建一个自定义 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/

相关文章:

android - 通过USB将两个android设备连接在一起

java - Selendroid "Error forwarding the new session cannot find : Capabilities"

android - 是否有与 RecyclerView 等效的 addHeaderView?

android - 在 fragment 中扩充布局

android - 如何获取 TabHost 中 Tab 的内容?

android - 如何在 android MVP 中应用组合?

android - Gradle实现/API没有获得子依赖项

android - SQLite for android 是否支持事务?

android - 如何将 SearchView 的输入类型设置为数字

android - 如何在android中创建一条闪烁的线?