gpt4 book ai didi

android - 我可以在 ViewModel 中使用 view.getContext() 作为我的数据绑定(bind)类吗

转载 作者:搜寻专家 更新时间:2023-11-01 08:21:45 24 4
gpt4 key购买 nike

我正在使用数据绑定(bind)和 MVVM 结构。

<layout >
<data>
<variable
name="loginVM"
type="drish.com.dsfaallstars.login.viewmodel.LoginViewModel"/>
</data>
...
<Button
android:id="@+id/loginButton"
android:textStyle="bold"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:background="@drawable/button"
android:text="@{loginVM.buttonText}"
android:textColor="@android:color/white"
android:onClick="@{(view)->loginVM.loginProcess(view,username.getText().toString(),password.getText().toString())}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline"
app:layout_constraintStart_toStartOf="@+id/guideline2"
app:layout_constraintTop_toBottomOf="@+id/textInputLayout3"
app:layout_constraintVertical_bias="0.19"/>
...
</layout>

在我的 ViewModel 中,我正在处理 onClick,在该方法中,我需要在某些要求下显示警告框,警告框需要 View 上下文,而不是应用程序上下文。

那么就这样吧,还是我应该采用任何其他更有效、更有帮助的方法。

public void loginProcess(View v, String user, String pass) {
Log.e(LogConst.TAG, "loginProcess: ");
Log.e(LogConst.TAG, " username " + user + "======= password " + pass);
if (user.length() < 1 || pass.length() < 1) {
new CustomLoginDialog(user, pass, v.getContext());
} else if (checkCredentialsOffline(user, pass)) {
Log.e(LogConst.TAG, "loginProcess: Async ");
new LoginTaskAsync(v, user, pass).execute();
}
}

最佳答案

使用 MVVM 的主要目的之一是使您的应用可测试。理想情况下,ViewModel 应该抽象出所有特定于 android 的依赖项,以便您可以为其业务逻辑编写非仪器测试。我创建了一个“Activity”接口(interface),在它后面放置了大多数特定于上下文的调用(例如“showDialog”),以便在需要时可以模拟它们。

关于android - 我可以在 ViewModel 中使用 view.getContext() 作为我的数据绑定(bind)类吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50325412/

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