Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

kotlin - Android Two Way DataBinding Problem of Ternary Operator Must be Constant

My EditText is like this:

<EditText
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@={viewModel.isAddCase? ``: `` + viewModel.currentStudent.age}"    //problem here
    android:inputType="number" />

I want the EditText not to show anything (empty String) based on the isAddCase variable, which is a MutableLiveData<Boolean> initilized when the ViewModel class object is created (inside the init{} block).

This is the error I got:

The expression '((viewModelIsAddCaseGetValue) ? ("") : (javaLangStringViewModelCurrentStudentAge))' cannot be inverted, so it cannot be used in a two-way binding

Details: The condition of a ternary operator must be constant: android.databinding.tool.writer.KCode@37a418c7

UPDATE

Even this doesn't work, shows the same error:

android:text="@={viewModel.currentStudent.age == 0? ``: `` + viewModel.currentStudent.age}"

I guess ternary operation just doesn't work well with two-way DataBinding.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to remove the equal sign before the starting curly brace

android:text="@{viewModel.isAddCase ? ``: `` + viewModel.currentStudent.age}"    

Also you can use String.valueOf instead of the ``

android:text="@{viewModel.isAddCase ? ``: String.valueOf(viewModel.currentStudent.age)}"    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...