Is there some way to provide android:maxLength
attribute via two-way databinding in Android application?
What i currently have is this in 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"/>
In view model i have these attributes:
/**
* Maximum length of message body.
*/
@Bindable
public int maxMessageLength;
/**
* Maximum length of reply message body.
*/
@Bindable
public int maxReplyLength;
Error thrown during build:
> 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 ****
I understand that this error is thrown because there is no simple set method for text length and it is usually provided via InputFilter
as described here:
How to programmatically set maxLength in Android TextView?
What i can imagine it to work would be something like:
android:maxLength="@={viewModel.replyLength}"
with
@Bindable
public InputFilter[] getReplyLength() {
return isInReplyMode() ? new InputFilter[] { new InputFilter.LengthFilter(maxReplyLength) } : new InputFilter[] { new InputFilter.LengthFilter(maxMessageLength) };
}
but it will not work for obvious reasons. It actually results into:
> 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 ****
So is there any possible way to data-bind max length attribute?