问题描述
我当前正在将 databinding
用于我的android应用程序项目。我想在 R.string.txtOldPassWordError
CustomTextView 中设置错误
消息code>并从另一个名为 ViewModelClass
的类进行设置。
I am currently using databinding
for my android application project. I want to set the error
message on my CustomTextView
from R.string.txtOldPassWordError
and set it up from another class called ViewModelClass
.
这是我的XML代码
<com.horseproject.widget.CustomEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginTop="@dimen/dp_20"
android:drawablePadding="@dimen/dp_10"
android:hint="@string/enter_old_password"
android:inputType="textPassword"
android:lines="1"
android:text="@={ChangePasswordVM.userOldPassword}"
android:textColorHint="@color/gray_text"
app:drawableLeftCompat="@drawable/ic_password_lock"
app:drawableTintCompat="@color/gray_app"
app:error="@{ChangePasswordVM.userOldPasswordError}" />
这是ViewModelClass.java
public class ChangePasswordViewModel extends BaseObservable {
public ObservableField<String> userOldPassword = new ObservableField<>("");
public void userPasswordChange() {
if ((TextUtils.isEmpty(userOldPassword.get()))) {
userOldPasswordError.set("Please enter your old password");
return;
} else if (userOldPassword.get().length() <= 5) {
userOldPasswordError.set("Password should contain minimum 6 characters");
return;
} else {
userOldPasswordError.set(null);
}
}
}
strings.xml
and this is string from strings.xml
<string name="select">Please Enter Old Password</string>
因此,我想在我的viewModel类中访问此字符串并将其设置为错误消息,而不是直接将其硬编码为字符串
。
So, I want to access this string in my viewModel class and set it as error message instead of hardcoded it directly as string
.
那么我该如何实现呢?我正在使用Android Studio 3.0 Beta版。
So how can i achieve this? I am using Android Studio 3.0 Beta Version. Any help would be really appreciated.
推荐答案
创建 ResourceProvider
类
public class ResourceProvider {
private Context mContext;
public ResourceProvider(Context mContext) {
this.mContext = mContext;
}
public String getString(int resId) {
return mContext.getString(resId);
}
public String getString(int resId, String value) {
return mContext.getString(resId, value);
}
}
现在转到您的 ApplicationClass
并粘贴
public class YourAppName extends Application {
// Resource Provider
private ResourceProvider mResourceProvider;
public ResourceProvider getResourceProvider() {
if (mResourceProvider == null)
mResourceProvider = new ResourceProvider(this);
return mResourceProvider;
}
}
现在转到您的 ChangePasswordViewModel
并创建ResourceProvider的对象
now go to your ChangePasswordViewModel
and create object of ResourceProvider
private ResourceProvider mResourceProvider;
并将其传递给 constroctor
的 ChangePasswordViewModel
您可以通过以下方式访问它
than you can access it by
userOldPasswordError.set(mResourceProvider.getString(R.string.select));
这篇关于如何在Android中的DataBinding的ViewModel类中获取R.string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!