数据绑定 - EditText 的 maxLength 属性

Databinding - maxLength attribute of EditText

有没有什么方法可以在 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 ****

那么有什么方法可以对最大长度属性进行数据绑定吗?

正如@pskink 在评论中指出的那样 - 我的问题是使用双向数据绑定而不是 maxLength 属性的数据绑定。应该有:

android:maxLength="@{viewModel.inReplyMode ? viewModel.maxReplyLength : viewModel.maxMessageLength}"

而不是

android:maxLength="@={viewModel.inReplyMode ? viewModel.maxReplyLength : viewModel.maxMessageLength}"

这就是 "no getter method for android:maxLength attribute of TextView" 异常的原因。