【发布时间】:2016-07-13 18:36:46
【问题描述】:
今天我在 Android Studio 预览版中发现了最近引入的 two-way data binding 功能,并决定试一试。
我有一个非常简单的布局(下面的代码),用于编写和发送消息。我想要实现的是在字段中没有输入文本时使用按钮“disabled”(并且将来会相应地有一些不同的图像)。
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="msg" type="String"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/new_message_input"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingStart="10dp"
android:hint="@string/hint_compose_message"
android:inputType="textAutoCorrect|textMultiLine"
android:text="@={msg}"/>
<ImageButton
android:id="@+id/btn_send_message"
android:layout_width="50dp"
android:layout_height="match_parent"
android:src="@drawable/ic_send"
android:enabled="@{!new_message_input.text.isEmpty()}"
android:clickable="@{!new_message_input.text.isEmpty()}"/>
</LinearLayout>
</layout>
第一个链接中的示例代码表明这样的内容应该足够了:
<layout ...>
<data>
<import type="android.view.View"/>
</data>
<RelativeLayout ...>
<CheckBox android:id="@+id/seeAds" .../>
<ImageView android:visibility="@{seeAds.checked ? View.VISIBLE : View.GONE}" .../>
</RelativeLayout>
</layout>
但是,当尝试为 ImageButton 的 enabled/clickable 属性实现类似的逻辑时,我收到以下错误:
错误:
java.lang.RuntimeException:java.lang.RuntimeException:发现数据绑定错误。 ****/ 数据绑定错误 ****msg:标识符必须具有来自 XML 文件的用户定义类型。new_message_input不见了
问题肯定出在这两行,因为删除它们可以正确创建绑定类。
我的问题是:
- 我做错了什么?
- 我该如何解决这个问题?
我也尝试了一些不同的方法,但结果是一样的:
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<import type="android.widget.EditText"/>
...
</data>
<LinearLayout
...
<ImageButton
...
android:enabled="@{!(((EditText)new_message_input).getText().toString().isEmpty())}"
android:clickable="@{!(((EditText)new_message_input).getText().toString().isEmpty())}"/>
【问题讨论】:
标签: android android-layout data-binding android-view 2-way-object-databinding