【问题标题】:In Android, can the value of a custom attribute be changed at runtime?在Android中,可以在运行时更改自定义属性的值吗?
【发布时间】:2014-10-28 19:22:03
【问题描述】:

我知道可以在 xml 中设置自定义属性及其值,但是, 以后可以在运行时更改该值吗?

我有这个 xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:example="http://schemas.android.com/apk/res/ValidatedButton.ValidatedButton"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <validatedbutton.ValidatedButton
        android:id="@+id/myButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/icon_selector"
        example:state_valid="false"
        android:text="@string/hello" />
</LinearLayout>

我想在运行时将 example:state_valid 更改为 true 或 false。

【问题讨论】:

    标签: runtime android-custom-attributes


    【解决方案1】:

    我知道这是一个老问题,但我最近也一直在尝试解决这个问题。

    事实上,Android MNC sdk 的发布为我们提供了许多使用 数据绑定 的巧妙功能。官方文档和指南可以在 here 找到,还有一个非常好的教程 here .

    我实际上并没有对此进行很多探索,但我相信现在可以通过使用这种新方法来解决最初的问题。让我知道这是否有帮助!

    【讨论】:

      【解决方案2】:

      不,你不能。

      但您可以在下面找到丑陋的解决方法:

      我认为你应该区分两种构建视图的方式:

      1. 从 xml 扩展 *static 布局
      2. 在 Java 中在运行时构建它

      在自定义视图的构造函数中,您可以获得布局中定义的静态属性值并将它们保存在自定义视图类字段中。然后存储在字段中的值用于构建您的视图。视图是在某些上下文中构建的(例如,在活动的上下文中),因此理论上您可以将上下文转换为自定义活动并获取信息,如果您想更改“属性值”,但您只会更改 Java 变量,而不是 xml 值。

      在我看来,如果您的视图是如此动态,以至于它会经常更改,您应该考虑在 XML 中放置一个简单的容器(例如 FrameLayout)。然后构建您的视图并在运行时将其添加到容器中。

      【讨论】:

        猜你喜欢
        • 2012-04-20
        • 2020-03-09
        • 1970-01-01
        • 2018-01-14
        • 2013-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-04
        相关资源
        最近更新 更多