2

我知道可以在 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。

4

2 回答 2

2

I know this is an old question, however it's something that I've recently been trying to figure out as well.

As it happens to be, the release of the Android MNC sdk has given us a lot of neat abilities with the use of Data Binding. The official documentation and guide can be found here, and a really good tutorial is available here.

I haven't actually explored this a lot, but I believe it's now possible to achieve the original question by using this new method. Lemme know if this helps!

于 2015-07-31T09:07:00.380 回答
0

不,你不能。

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

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

  1. 从 xml膨胀*static布局
  2. 在 Java运行时构建它

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

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

于 2014-12-12T15:00:19.897 回答