【问题标题】:Complex Attributes in Android Custom View XMLAndroid 自定义视图 XML 中的复杂属性
【发布时间】:2014-04-30 08:42:42
【问题描述】:


我有一个关于自定义视图 XML 声明的问题。
我像往常一样使用自定义属性创建了自己的视图。现在我想添加更复杂的属性,如下所示:(这是非工作代码)

<com.xxx.yyy.CustomTextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/customTextView1"
    android:layout_marginBottom="22dp"
    android:layout_toRightOf="@+id/buttonBlack"
    android:text="TextView" >
        <Animation
            animation:property1="123"
            animation:property2="456" />
        <Animation
            animation:property1="789"
            animation:property2="012" >
        </Animation>
</com.xxx.yyy.CustomTextView>

我自己没有找到办法,但也许有人有想法。

谢谢!


编辑:

我只是或多或少地很好地解决了这个问题。 我在名为 animations.xml 的 /res/xml 文件夹中创建了一个新的 .xml 文件

<animations>
    <animation
        name="Animation name 1"
        float1="1.1"
        float2="1.2"
        integer1="11"
        integer2="12" />
    <animation
        name="Animation name 2"
        float1="2.1"
        float2="2.2"
        integer1="21"
        integer2="22" />
</animations>

我在 attrs.xml 中的自定义视图包含一个用于从上面引用 animations.xml 文件的属性:

<declare-styleable name="MyTextView">
    <attr name="animations" format="reference" />
</declare-styleable>

现在我在 MyTextView 的构造函数中解析引用的 .xml 文件,如下所述:http://thedevelopersinfo.com/2009/12/14/using-xml-file-resources-in-android/

也许这有时会帮助某人。

【问题讨论】:

标签: android xml view android-custom-view


【解决方案1】:

除非CustomTextView 扩展ViewGroup(或在它的类层次结构中)并且Animation 是您定义的自定义视图,否则这将不起作用。布局 XML 文件中只允许使用 ViewsViewGroups(以及 Android 定义的一些特殊标签,如 includemerge),并且只有 ViewGroup 元素可以有子元素。

【讨论】:

  • 好的,谢谢!这正是我的想法。我只是希望有一种我还没有见过的方法。
【解决方案2】:

您可以像这样将自定义 XML 属性添加到自定义视图中:

<resources>

<declare-styleable name="YourCustomClass">
    <attr name="someCustomAnimationAttribute" format="reference" />
</declare-styleable>

<resources>

这里描述了如何获得它:

http://developer.android.com/training/custom-views/create-view.html#applyattr

在你的布局中你必须声明一个命名空间:

xmlns:app="http://schemas.android.com/apk/res-auto"

然后像这样使用它:

<com.xxx.yyy.CustomTextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/customTextView1"
android:layout_marginBottom="22dp"
android:layout_toRightOf="@+id/buttonBlack"
android:text="TextView" 
app:someCustomAnimationAttribute="@drawable/someAnimation">

这样您就可以通过 XML 提供这些动画,而不是将它们作为子元素添加,这是不可能的。

【讨论】:

  • 我认为 OP 的主要关注点是如何在自定义视图中检索子 xml 标签,即&lt;Animation /&gt;
  • 正如@Karakuri 指出的那样,如果该自定义视图扩展ViewGroup,则可以添加子视图(具有自定义参数的自定义子视图)。但是以这种方式提供动画是行不通的。
  • 是的。我已经知道如何定义简单的属性。问题是是否可以将更复杂的属性定义为 XML 子元素。不过还是谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 2013-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多