【问题标题】:Custom Type attributes for a custom android view自定义 android 视图的自定义类型属性
【发布时间】:2013-08-20 12:33:23
【问题描述】:

我想创建一个自定义 Android 视图 (MyCustomView)。在这个 View 中,我想要一个自定义类型 (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>

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

谢谢!

【问题讨论】:

  • 感谢您的评论,但是从 XML 设置的 CUSTOM TYPE 属性没有任何内容。关于如何创建字符串、整数、布尔值、引用等类型的自定义属性只有一个参考,请仔细阅读问题。
  • 好的。你不能。看我的回答

标签: android android-view


【解决方案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);

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 2011-10-12
      相关资源
      最近更新 更多