2013-02-27 25 views
11

如何將父級視圖中的自定義屬性的值級聯到其子視圖?將父視圖中的自定義屬性的值級聯到子視圖?

這是最簡單的使用一個例子來解釋:

<com.example.CustomLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    app:percent="35" > 

    <com.example.CustomView 
     android:id="@+id/customView1" 
     app:percent="how-to-get-app:percent-value-here???" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 

</com.example.CustomLayout> 

這裏,CustomLayout延伸LinearLayout。我使用<declare-styleable>元素在attrs.xml中定義了自定義屬性「percent」。正如你所看到的,我在XML中爲CustomLayout設置了35%。

我現在想要傳遞相同的值到CustomView(它擴展了View),並且我將包含在CustomLayout中。我無法找到一種在XML中執行此操作的方法(雖然在代碼中執行此操作很容易)。

我嘗試以下:

app:percent="@attr/percent"

app:percent="?attr/percent"

TypedArray#getInt()

這些(預期地)失敗,NumberFormatException兩者。

那麼,關於如何讓這個工作的任何想法?

+0

你已經找到了解決?也有任何機會@CommonsWare你有沒有嘗試過這樣的事情?我真的沒有想法如何讓這個工作... – 2015-02-26 15:43:35

+0

@AntonioE。沒有,從來沒有找到方法。代之以Java代碼結束。 – curioustechizen 2015-02-26 17:04:49

+0

對此沒有答案感到失望。 – Everett 2015-04-02 06:01:10

回答

1

雖然這個想法來得有點遲,而且這個方法並不簡單,但我認爲它仍然值得分享。我們可以將自定義屬性放入主題中,以便可以將屬性從使用主題的父視圖傳遞到所有子視圖(即屬性存在於視圖組中)。

舉例如下:

<integer name="percentage">35</integer> 

<style name="CustomTheme" parent="suitable theme for your case"> 
    <item name="percent">@integer/percentage</item> 
</style> 

<com.example.CustomLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:theme="@style/CustomTheme" > 

    <com.example.CustomView 
     android:id="@+id/customView1" 
     app:percent="?attr/percent" <!--Note: that's how it refers to the value, 
     however, re-assign the attribute value here is meaningless as attribute percent 
     should exist in all child views now. You can retrieve its value via 
     Theme.obtainStyledAttributes(R.style.CustomTheme, new int[] {R.attr.percent}) 
     in every child view--> 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 
</com.example.CustomLayout> 
相關問題