我在通过viewModel(+ dataBinding inside)向我的editText字段添加错误时遇到问题 这是我的活动: 类RegisterActivity:BaseActivityFullscreen(){
var binding: ActivityRegisterBinding? = null
var viewmodel: RegisterViewModel? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, tv.hotpot.luve.R.layout.activity_register)
viewmodel = ViewModelProviders.of(this).get(RegisterViewModel::class.java)
binding?.viewmodel = viewmodel
}
这是我要在其中添加错误的editText:
<EditText
android:hint="@string/email_address"
android:text="@={viewmodel.email}"
android:onTextChanged="@{viewmodel::onEmailChanged}"
android:layout_width="342dp"
android:backgroundTint="#40FFFFFF"
android:textColorHint="#99FFFFFF"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="@+id/email_address"
android:textColor="@android:color/white"
android:selectAllOnFocus="true" android:gravity="center" android:textSize="16sp"
android:layout_marginStart="8dp" app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="8dp" android:layout_marginEnd="8dp" app:layout_constraintEnd_toEndOf="parent"
android:layout_marginRight="8dp"
android:paddingBottom="24dp"
android:layout_marginTop="50dp" app:layout_constraintTop_toTopOf="@+id/password"/>
这是viewModel:
class RegisterViewModel : ViewModel() {
private val parentJob = Job()
private val coroutineContext: CoroutineContext
get() = parentJob + Dispatchers.Default
private val scope = CoroutineScope(coroutineContext)
private val repository : HotpotRepository= HotpotRepository(HotpotAPI.api)
var authToken: String? = "no token"
var userId: Long? = null
// binding stuff
var btnSelected: ObservableBoolean? = ObservableBoolean(false)
var email: ObservableField<String>? = ObservableField("")
var password: ObservableField<String>? = ObservableField("")
// end of binding stuff
//functions checking to disable button
fun onEmailChanged(s: CharSequence, start: Int, befor: Int, count: Int) {
btnSelected?.set(Util.isEmailValid(s.toString()) && password?.get()!!.length >= 8)
}
我最初在viewModel中将错误消息变量设置为
var errorMessage: ObservableField<String>? = ObservableField("")
并在xml中像这样使用它
android:error="@{viewmodel.errorMessage}"
并在onEmailChanged中对其进行了更新:
errorMessage.set("Too short input")
即使输入一个字母,该错误也可以显示,并且更新并显示“输入太短”,但是在该字段自动清除错误之后,该错误会完全消失。有没有一种方法可以解决它,使其在清除后更新,还是需要以其他方式进行? 预先谢谢你!