3
有没有办法通过Android应用程序中的双向数据绑定来提供android:maxLength
属性?Databinding - EditText的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 ****
我明白引发此错误是因为没有简单的文本长度设置方法,通常通过0123提供如下所述: 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: [email protected]
file:...\app\src\main\res\layout\f_message_compose.xml
loc:74:50 - 74:126
****\ data binding error ****
那么有什么可能的方式来数据绑定最大长度属性?
“android:maxLength”有一个'BindingAdapter',参见:http://androidxref.com/7.1.1_r6/xref/frameworks/data-binding/extensions/baseAdapters/src/main/java/android/数据绑定/适配器/ TextViewBindingAdapter.java#238,你需要什么双向绑定? – pskink
好吧,如果我理解正确的话,这个适配器应该默认使用。 无论如何,你的问题导致我的问题。看起来我不应该在属性前加'@ =',而只使用'@'!这就是数据绑定和双向数据绑定之间的区别。似乎我错过了规范:) –
'@ ='是用于例如。 'EditText'想要绑定某些模型字符串并将其显示为内容,并在更改时将其更改为映射到字符串模型 – pskink