簡體   English   中英

將自定義屬性的值從父視圖級聯到子視圖?

[英]Cascade the value of a custom attribute from a parent view to a child view?

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

使用示例最容易解釋:

<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”。 如您所見,我在CustomLayout的XML中將百分比設置為35。

我現在想要將相同的值傳遞給CustomView (它擴展View ),我將包含在CustomLayout 我無法找到在XML中執行此操作的方法(盡管在代碼中很容易這樣做)。

我嘗試了以下方法:

app:percent="@attr/percent"

app:percent="?attr/percent"

TypedArray#getInt() ,這兩個(預期)都會因NumberFormatException失敗。

那么,關於如何使其發揮作用的任何想法?

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

示例如下:

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM