Android自定义视图XML中的复杂属性

时间:2014-04-30 08:42:43

标签: android xml view android-custom-view


我对自定义视图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>

我没有找到办法自己做这件事,但也许有人有个主意。

谢谢!


修改:

我或多或少地解决了这个问题。 我在/ res / xml文件夹中创建了一个名为animations.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/

也许这会在某个时候帮助某人。

2 个答案:

答案 0 :(得分:1)

除非CustomTextView扩展ViewGroup(或将其置于其类层次结构中)并且Animation是您定义的自定义视图,否则这将无效。布局XML文件中只允许ViewsViewGroups(以及Android定义的一些特殊标记,如includemerge),只有ViewGroup元素可以包含子元素。< / p>

答案 1 :(得分:1)

您可以将自定义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提供这些动画,而不是将它们作为子元素添加,这是不可能的。