【发布时间】:2017-07-27 21:06:02
【问题描述】:
有没有办法在 Android 应用程序中通过双向数据绑定提供android:maxLength 属性?
我目前拥有的是 XML 格式:
<EditText
android:id="@+id/edBody"
style="@style/SimpleEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"
android:hint="@string/ComposeMessage"
android:text="@={viewModel.composeFace.body}"
android:maxLength="@={viewModel.inReplyMode ? viewModel.maxReplyLength : viewModel.maxMessageLength}"
android:afterTextChanged="@{viewModel.autoWatch}"
android:imeOptions="actionNext"
android:inputType="textMultiLine"/>
在视图模型中我有这些属性:
/**
* Maximum length of message body.
*/
@Bindable
public int maxMessageLength;
/**
* Maximum length of reply message body.
*/
@Bindable
public int maxReplyLength;
构建过程中抛出的错误:
> java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:Cannot find the getter for attribute 'android:maxLength' with value type int on android.widget.EditText.
file:...\app\src\main\res\layout\f_message_compose.xml
loc:66:20 - 77:65
****\ data binding error ****
我了解引发此错误是因为没有简单的文本长度设置方法,并且通常通过InputFilter 提供,如下所述:
How to programmatically set maxLength in Android TextView?
我可以想象它的工作方式如下:
android:maxLength="@={viewModel.replyLength}"
与
@Bindable
public InputFilter[] getReplyLength() {
return isInReplyMode() ? new InputFilter[] { new InputFilter.LengthFilter(maxReplyLength) } : new InputFilter[] { new InputFilter.LengthFilter(maxMessageLength) };
}
但由于显而易见的原因,它不起作用。它实际上导致:
> java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:The expression ((viewModelInReplyMode) ? (viewModelMaxReplyLength) : (viewModelMaxMessageLength)) cannot cannot be inverted: The condition of a ternary operator must be constant: android.databinding.tool.writer.KCode@7f305219
file:...\app\src\main\res\layout\f_message_compose.xml
loc:74:50 - 74:126
****\ data binding error ****
那么有没有可能的方法来绑定最大长度属性?
【问题讨论】:
-
android:maxLength有一个BindingAdapter,见:androidxref.com/7.1.1_r6/xref/frameworks/data-binding/…,你需要双向绑定做什么? -
好吧,如果我理解正确的话,应该默认使用这个适配器。无论如何,您的问题使我遇到了问题。看来我不应该把
@=放在属性前面,而只使用@!这就是数据绑定和双向数据绑定之间的区别。好像我在规范中错过了它:) -
@=用于 ex。EditText想要绑定一些模型字符串并将其显示为内容并在更改时返回,更改应映射到字符串模型 -
是的,我现在明白了其中的区别,这显然是由于我对数据绑定语法的疏忽造成的,因此使用 2 路数据绑定而不是简单的数据绑定来处理不适当的属性。谢谢你指出:)
-
如果您使用其中一个 cmets 解决了您的问题,请自行回答您的问题,而不是编辑。
标签: java android data-binding android-databinding