[英]Cascade the value of a custom attribute from a parent view to a child view?
How do I "cascade" the value of a custom attribute from a parent view to its child view? 如何将自定义属性的值从父视图“级联”到其子视图?
This is easiest to explain using an example: 使用示例最容易解释:
<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>
Here, CustomLayout
extends LinearLayout
. 在这里, CustomLayout
扩展了LinearLayout
。 I have defined a custom attribute "percent" in attrs.xml
using <declare-styleable>
element. 我使用<declare-styleable>
元素在attrs.xml
定义了一个自定义属性“percent”。 As you can see, I set percent to 35 in the XML for CustomLayout
. 如您所见,我在CustomLayout
的XML中将百分比设置为35。
I now want to pass in the same value to CustomView
(which extends View
) and which I will include in CustomLayout
. 我现在想要将相同的值传递给CustomView
(它扩展View
),我将包含在CustomLayout
。 I am unable to find a way to do this in XML (it is easy to do this in code though). 我无法找到在XML中执行此操作的方法(尽管在代码中很容易这样做)。
I tried the following: 我尝试了以下方法:
app:percent="@attr/percent"
app:percent="?attr/percent"
Both of these (expectedly) fail with NumberFormatException
at TypedArray#getInt()
. 在TypedArray#getInt()
,这两个(预期)都会因NumberFormatException
失败。
So, any ideas on how to get this to work? 那么,关于如何使其发挥作用的任何想法?
Although the idea comes a bit late and the method is not straight forward, I think it's still worth sharing. 虽然这个想法有点迟了,而且方法并不简单,但我认为它仍然值得分享。 We can put custom attributes into a theme, so the attributes can be passed to all child views from the parent view where the theme is used (ie, the attributes exist within the View Group). 我们可以将自定义属性放入主题中,因此可以将属性从使用主题的父视图传递给所有子视图(即视图组中存在属性)。
Example as follows: 示例如下:
<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.