2013-02-27 8 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> 

CustomLayoutLinearLayoutを拡張します。 attrs.xmlにカスタム属性 "パーセント"を定義して、<declare-styleable>要素を使用しています。ご覧のとおり、CustomLayoutのXMLで%を35に設定しました。

CustomView(これはViewになります)に同じ値を渡したいと思います。これはCustomLayoutに含まれます。私はXMLでこれを行う方法を見つけることができません(コードでこれを行うのは簡単です)。

Iは、次の試み:

app:percent="@attr/percent"

app:percent="?attr/percent"

これらの両方(予想通り)TypedArray#getInt()NumberFormatExceptionで失敗します。

これはどのように動作させるためのアイデアですか?

+0

あなたは解決策を見つけたことがありますか?また、万が一、@ CommonSWareはこれまで何か試したことがありますか?私は実際にこの作業をする方法のアイデアがありません... –

+0

@AntonioE。いいえ、方法を見つけたことはありません。代わりにJavaコードでそれをやり終えた。 – curioustechizen

+0

答えがないことに失望しました。 – Everett

答えて

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> 
関連する問題