gpt4 book ai didi

android - 如何使用 ViewModel 和 Databinding 实现验证?

转载 作者:IT老高 更新时间:2023-10-28 13:42:43 26 4
gpt4 key购买 nike

使用 ViewModel 和数据绑定(bind)验证表单数据的最佳方法是什么?

我有一个简单的注册 Activity ,它链接绑定(bind)布局和 ViewModel

class StartActivity : AppCompatActivity() {

private lateinit var binding: StartActivityBinding
private lateinit var viewModel: SignUpViewModel

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

viewModel = ViewModelProviders.of(this, SignUpViewModelFactory(AuthFirebase()))
.get(SignUpViewModel::class.java);

binding = DataBindingUtil.setContentView(this, R.layout.start_activity)
binding.viewModel = viewModel;

signUpButton.setOnClickListener {

}
}
}

ViewModel 带有 4 个 ObservableFieldssignUp() 方法,应该在向服务器提交数据之前验证数据。

class SignUpViewModel(val auth: Auth) : ViewModel() {
val name: MutableLiveData<String> = MutableLiveData()
val email: MutableLiveData<String> = MutableLiveData()
val password: MutableLiveData<String> = MutableLiveData()
val passwordConfirm: MutableLiveData<String> = MutableLiveData()

fun signUp() {

auth.createUser(email.value!!, password.value!!)
}
}

我想我们可以为每个输入添加四个 bool ObservableFields,在 signUp() 中我们可以检查输入并更改 bool ObservableField 的状态,这将在布局上产生出现错误

val isNameError: ObservableField<Boolean> = ObservableField()


fun signUp() {

if (name.value == null || name.value!!.length < 2 ) {
isNameError.set(true)
}

auth.createUser(email.value!!, password.value!!)
}

但我不确定 ViewModel 是否应该负责验证并向用户显示错误,我们会有样板代码

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>

<import type="android.view.View" />

<variable
name="viewModel"
type="com.maximdrobonoh.fitnessx.SignUpViewModel" />
</data>

<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorGreyDark"
android:orientation="vertical"
android:padding="24dp">

<TextView
android:id="@+id/appTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/app_title"
android:textColor="@color/colorWhite"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<LinearLayout
android:id="@+id/screenTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/appTitle">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="4dp"
android:text="@string/sign"
android:textColor="@color/colorWhite"
android:textSize="26sp"
android:textStyle="bold" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/up"
android:textColor="@color/colorWhite"
android:textSize="26sp" />
</LinearLayout>

<LinearLayout
android:id="@+id/form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="24dp"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/screenTitle">

<android.support.v7.widget.AppCompatEditText
style="@style/SignUp.InputBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/sign_up_name"
android:inputType="textPersonName"
android:text="@={viewModel.name}" />

<android.support.v7.widget.AppCompatEditText
style="@style/SignUp.InputBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/sign_up_email"
android:inputType="textEmailAddress"
android:text="@={viewModel.email}"
/>

<android.support.v7.widget.AppCompatEditText
style="@style/SignUp.InputBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/sign_up_password"
android:inputType="textPassword"
android:text="@={viewModel.password}" />

<android.support.v7.widget.AppCompatEditText
style="@style/SignUp.InputBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/sign_up_confirm_password"
android:inputType="textPassword"
android:text="@={viewModel.passwordConfirm}" />

<Button
android:id="@+id/signUpButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="@drawable/button_gradient"
android:text="@string/sign_up_next_btn"
android:textAllCaps="true"
android:textColor="@color/colorBlack" />

</LinearLayout>

</android.support.constraint.ConstraintLayout>
</layout>

最佳答案

有很多方法可以实现这一点。我告诉你两个解决方案,都很好,你可以使用你认为适合你的。

我使用 extends BaseObservable 因为我发现这比将所有字段转换为 Observers 容易。你也可以使用 ObservableFields

方案一(使用自定义BindingAdapter)

在 xml 中

<variable
name="model"
type="sample.data.Model"/>

<EditText
passwordValidator="@{model.password}"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@={model.password}"/>

Model.java

public class Model extends BaseObservable {
private String password;

@Bindable
public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
notifyPropertyChanged(BR.password);
}
}

DataBindingAdapter.java

public class DataBindingAdapter {
@BindingAdapter("passwordValidator")
public static void passwordValidator(EditText editText, String password) {
// ignore infinite loops
int minimumLength = 5;
if (TextUtils.isEmpty(password)) {
editText.setError(null);
return;
}
if (editText.getText().toString().length() < minimumLength) {
editText.setError("Password must be minimum " + minimumLength + " length");
} else editText.setError(null);
}
}

解决方案2(使用自定义afterTextChanged)

在 xml 中

<variable
name="model"
type="com.innovanathinklabs.sample.data.Model"/>

<variable
name="handler"
type="sample.activities.MainActivityHandler"/>

<EditText
android:id="@+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:afterTextChanged="@{(edible)->handler.passwordValidator(edible)}"
android:text="@={model.password}"/>

MainActivityHandler.java

public class MainActivityHandler {
ActivityMainBinding binding;

public void setBinding(ActivityMainBinding binding) {
this.binding = binding;
}

public void passwordValidator(Editable editable) {
if (binding.etPassword == null) return;
int minimumLength = 5;
if (!TextUtils.isEmpty(editable.toString()) && editable.length() < minimumLength) {
binding.etPassword.setError("Password must be minimum " + minimumLength + " length");
} else {
binding.etPassword.setError(null);
}
}
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setModel(new Model());
MainActivityHandler handler = new MainActivityHandler();
handler.setBinding(binding);
binding.setHandler(handler);
}
}

更新

你也可以替换

android:afterTextChanged="@{(edible)->handler.passwordValidator(edible)}"

android:afterTextChanged="@{handler::passwordValidator}"

因为 android:afterTextChangedpasswordValidator 的参数相同。

关于android - 如何使用 ViewModel 和 Databinding 实现验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52371374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com