【问题标题】:Cascade the value of a custom attribute from a parent view to a child view?将自定义属性的值从父视图级联到子视图?
【发布时间】: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。我使用&lt;declare-styleable&gt; 元素在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


【解决方案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>

【讨论】:

    猜你喜欢
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多