大家好,我的ViewModel类中的自定义视图有可能获得Observable吗?
自定义视图是此处的国家/地区选择器:https://github.com/hbb20/CountryCodePickerProject
也许可以更好地实现从CustomView获取Observable的方法,请告诉我。
我的活动,ViewModel和布局如下:
class EmployeeViewModel : BaseViewModel() {
val status = SingleLiveEvent<Status>()
val email = ObservableField<String>()
val phone = ObservableField<String>()
fun buttonClicked() {
if (!emailIsValid(email.get())){
status.value = Status.EMPTY_EMAIL_FIELD
}
if (!phoneIsValid(phone.get())){
status.value = Status.EMPTY_PHONE_FIELD
}
// here should be code to validate Country Code custom view
// maybe something like this.
if(phonePicker.getDefaultCountryCode() == WHATEVER){
//
}
}
}
XML布局
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.EmployeeActivity">
<data>
<variable
name="viewModel"
type="com.example.EmployeeViewModel" />
</data>
<TextView
android:id="@+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@={viewModel.email}" />
<TextView
android:id="@+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@={viewModel.phone}" />
<com.hbb20.CountryCodePicker
android:id="@+id/phonePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:ccp_showNameCode="false"
app:ccp_showPhoneCode="false" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{() -> viewModel.buttonClicked()}"
android:text="Validate Employee" />
</layout>
活动
class EmployeeActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val databinding = DataBindingUtil.setContentView<ActivityEmployeeBinding>(this, R.layout.activity_employee)
databinding.viewModel = withViewModel {
observe(status) { handleStatus(it) }
}
databinding.executePendingBindings()
}
private fun handleStatus(status: Status?) {
when (status) {
Status.EMPTY_EMAIL_FIELD -> Toast.makeText(activity, "Please enter your email name!", Toast.LENGTH_SHORT).show()
Status.EMPTY_PHONE_FIELD -> Toast.makeText(activity, "Please enter your phone", Toast.LENGTH_SHORT).show()
Status.EMPTY_INLAVID_PHONE_FIELD -> Toast.makeText(activity, "Please enter a valid phone", Toast.LENGTH_SHORT).show()
}
}
}
感谢您的回复。