【发布时间】:2016-09-23 11:28:23
【问题描述】:
如何将自定义属性的值从父视图“级联”到其子视图?
这是最容易用一个例子来解释的:
<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 中定义了一个自定义属性“百分比”。如您所见,我在 CustomLayout 的 XML 中将百分比设置为 35。
我现在想将相同的值传递给CustomView(扩展View)并将其包含在CustomLayout 中。我无法找到在 XML 中执行此操作的方法(尽管在代码中很容易执行此操作)。
我尝试了以下方法:
app:percent="@attr/percent"
app:percent="?attr/percent"
这两个(预期)都失败了NumberFormatExceptionTypedArray#getInt()。
那么,关于如何让它发挥作用的任何想法?
【问题讨论】:
-
您找到解决方案了吗?也有任何机会@CommonsWare 你曾经尝试过这样的事情吗?我真的不知道如何让这个工作......
-
@AntonioE。不,从来没有找到方法。最终改用 Java 代码。
-
对此没有答案感到失望。
-
我认为如果您在父视图中以编程方式创建子视图,则可以传递 attrs。
-
@curioustechizen,你是如何使用代码实现的?
标签: android android-custom-view