2013-02-27 67 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> 
相关问题