Android 是否将自定义属性的值从父视图级联到子视图?
如何将自定义属性的值从父视图“级联”到其子视图 用一个例子最容易解释这一点:Android 是否将自定义属性的值从父视图级联到子视图?,android,android-custom-view,Android,Android Custom 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_heigh
<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
。我使用
元素在attrs.xml
中定义了一个自定义属性“百分比”。如您所见,我在XML中将CustomLayout
的百分比设置为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>
35
@整数/百分比
你找到解决办法了吗?顺便问一下@commonware你有没有试过这样的东西?“我真的不知道如何让它工作……”安东尼奥。没有,从来没有找到办法。最终用Java代码完成了。对此没有答案,我感到失望。我认为如果您在父视图中以编程方式创建子视图,然后可以传递属性,这是可能的。@curioustechizen,您如何使用代码完成此任务?