How to Get R.string in ViewModel Class of DataBinding in Android
Create ResourceProvider
class
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);
}
}
now go to your ApplicationClass
and paste
public class YourAppName extends Application {
// Resource Provider
private ResourceProvider mResourceProvider;
public ResourceProvider getResourceProvider() {
if (mResourceProvider == null)
mResourceProvider = new ResourceProvider(this);
return mResourceProvider;
}
}
now go to your ChangePasswordViewModel
and create object of ResourceProvider
private ResourceProvider mResourceProvider;
and pass it in constroctor
of ChangePasswordViewModel
than you can access it by
userOldPasswordError.set(mResourceProvider.getString(R.string.select));
Using an ObservableInt worked for me. Adding this to the ViewModel
private final ObservableInt mErrorText = new ObservableInt(R.string.empty_text);
public ObservableInt getErrorText() {
return mErrorText;
}
And just setting a new String value
mErrorText.set(R.string.text_not_valid);
In the xml add the following to the TextView
android:text="@{viewModel.errorText}"