2014-04-30 39 views
0


我對自定義視圖XML聲明有個疑問。
我用正常的自定義屬性創建了自己的View。現在,我想補充這樣的更復雜的屬性:(這是不工作的代碼)Android自定義視圖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

<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文件的屬性我/ RES/XML文件夾中創建一個新的.xml文件

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

現在我解析引用的.xml文件在MyTextView的構造如下所述:http://thedevelopersinfo.com/2009/12/14/using-xml-file-resources-in-android/

也許這可以幫助別人,在一段時間。

+0

您應該爲此創建自定義XML屬性,如此處所述:http://developer.android.com/training/custom-views/create-view.html#applyattr – JimmyVanBraun

回答

1

除非CustomTextView延伸ViewGroup(或在它的類層次結構中)並且Animation是您定義的自定義視圖,否則這將不起作用。只有ViewsViewGroups被允許在佈局XML文件中(以及一些由Android定義的特殊標記,如includemerge),並且只有ViewGroup元素可以具有子元素。

+0

好的,謝謝!這正是我的想法。我只是希望有一種做法,我還沒有看到。 – p0wl90

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提供這些動畫,而不是將它們添加爲子元素,這是不可能的。

+0

我認爲OP的主要關注點是如何在自定義視圖中檢索子xml標籤,即'' – waqaslam

+0

正如@Karakuri指出的那樣,如果該自定義視圖擴展了'ViewGroup',則可以添加子視圖(自定義子視圖自定義參數)。但以這種方式提供動畫將無法工作。 – JimmyVanBraun

+0

是的。我已經知道如何定義簡單的屬性。問題是是否可以將更復雜的屬性定義爲XML子元素。不過謝謝! – p0wl90

相關問題