I am making a password creation screen, and I want to show a password strength indicator as they type.
My layout looks like this:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="com.example.PasswordViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:textChangedListener="#{viewModel.passwordTextWatcher}" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#{viewModel.passwordQuality}"/>
</LinearLayout>
</layout>
PasswordViewModel.java is like below
public class PasswordViewModel extends BaseObservable {
private String password;
#Bindable
public String getPasswordQuality() {
if (password == null || password.isEmpty()) {
return "Enter a password";
} else if (password.equals("password")) {
return "Very bad";
} else if (password.length() < 6) {
return "Short";
} else {
return "Okay";
}
}
public void setPassword(String password) {
this.password = password;
notifyPropertyChanged(BR.passwordQuality);
}
#Bindable
public TextWatcher getPasswordTextWatcher() {
return new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Do nothing.
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
setPassword(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
// Do nothing.
}
};
}
And Finally
public class EditTextBindingAdapters {
#BindingAdapter("textChangedListener")
public static void bindTextWatcher(EditText editText, TextWatcher textWatcher) {
editText.addTextChangedWatcher(textWatcher);
}
}
But when I start to write onTextChanged method is not calling! can anyone help me to resolve this issue? thanks, in advance.
According your description of problem, it seems you did not initialized binding in your activity. if this is the case then
First check that you have initialized the binding in your activity and set the ViewModel on it like below
ActivityMainBinding activityMainBinding = null;
PasswordViewModel passwordViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
passwordViewModel = new PasswordViewModel();
activityMainBinding.setViewModel(passwordViewModel);
}
Now the second problem is addTextChangedWatcher, add addTextChangedListener in place of that.
like this
public class EditTextBindingAdapters {
#BindingAdapter("textChangedListener")
public static void bindTextWatcher(EditText editText, TextWatcher textWatcher) {
editText.addTextChangedListener(textWatcher);
}
}
Related
I am just learning about RxJava in Android and the (supposed) excellent composition of MVVM, databinding and RxJava. Unfortunately I cannot bind an RxJava Observable directly to a View: need a LiveData.
So, I was wondering is there a way to implement Two-way databinding with RxJava?
So far I've attempted to write a BindingAdapter which adds a listener to the passed View and calls onNext on the Subject.
#BindingAdapter("rxText")
public static void bindReactiveText(EditText view, BehaviorSubject<String> text)
{
view.setText(text.getValue());
view.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
text.onNext(s.toString());
}
});
}
What this does is updates the Subject/model with any changes in the View, so model always has consistent value with the View. However, the binding is never triggered for any change in the Subject itself (ofcourse we'd have to compare new and old values to stop from looping).
Now, I did try to subscribe to the subject and call setText for each emission, but then I'd have to dispose the Observer. So what I did was also listened for View Attach State change: subscribe in onViewAttachedToWindow and dispose the observer in onViewDetachedFromWindow.
#BindingAdapter("rxText")
public static void bindReactiveText(EditText editText, BehaviorSubject<String> text)
{
setText(editText, text.getValue());
editText.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
text.onNext(s.toString());
}
};
private Disposable disposable;
#Override
public void onViewAttachedToWindow(View v) {
editText.addTextChangedListener(textWatcher);
disposable = text.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.filter(s -> !s.equals(editText.getText().toString()))
.subscribe(s -> setText(editText, text.getValue()));
}
#Override
public void onViewDetachedFromWindow(View v) {
disposable.dispose();
editText.removeTextChangedListener(textWatcher);
}
});
}
And while that does work in the intended way, I'm not sure if this is the best approach to implement Two-way binding via RxJava.
One of the immediate drawback that comes into mind is, Activity/Fragment cannot register a for a callback for most android Views. For instance, if I use the same approach for a Button and its click, and set up a listener in my Activity the binding will stop working.
I am still learning RxJava and its various operators and their uses, so maybe I'm missing something obvious or committing a goof, but I've been trying to working out another way to do this for a few days now, so far have not been able to think of one.
So my question: What is the best approach to implementing Two-way data binding with RxJava Observables.
To bind RxJava Observable directly to a View, you need to use ObservableField:
val name = ObservableField<String>()
//ex: name = "john"
Then put this in your xml:
<data>
<import type="android.databinding.ObservableField"/>
<variable
name="name"
type="ObservableField<String>" />
</data>
<TextView
android:text="#{name}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Reference: https://developer.android.com/topic/libraries/data-binding/observability
EDIT:
In case you need to apply it on a model instead of a single field, you can do this:
class User : BaseObservable() {
#get:Bindable
var firstName: String = ""
set(value) {
field = value
notifyPropertyChanged(BR.firstName)
}
#get:Bindable
var lastName: String = ""
set(value) {
field = value
notifyPropertyChanged(BR.lastName)
}
}
BR is the name of a class generated by Android Data Binding.
I would not recommend you to do it like that. While usage of Rx Java with data binding is good(LiveData is better though), your way of implementing it is quite overworked.
This is enough to bind it to the textView.
#BindingAdapter("rxText")
public static void bindReactiveText(EditText view, BehaviorSubject<String> text)
{
view.setText(text.getValue());
view.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
text.onNext(s.toString());
}
});
}
To subscribe to it and use it you should use a bit different approach. You should use it in view model that should look like this
public class MyViewModel extends ViewModel {
private CompositeDisposable subscriptions = new CompositeDisposable();
public BehaviorSubject<String> text = new BehaviorSubject<String>();
private void bind() {
subscriptions.add(
text.subscribe(text -> {
//do something
})
)
}
#Override
public void onCleared(){
subscriptions.clear()
}
}
and in layout use
...
<TextView
android:id="#+id/text"
style="#style/TextField.Subtitle3.Primary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/small_margin"
app:rxText="#{vm.text}"
/>
...
and in fragment
public class MasterFragment extends Fragment {
private MyViewModel vm;
public void onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewDataBinding binding = DataBindingUtil.inflate(inflater, layoutRes, container, false);
model = new ViewModelProvider(requireActivity()).get(MyViewModel.class);
binding.setVariable(BR.vm, this);
binding.executePendingBindings();
vm.bind();
return binding.root;
}
}
I would do something like this if I would use RxJava for that. I am using LiveData though.
Hope it helps.
I am trying to create a custom component that is made up of lots of other components. I need to be able to use it the same way I would a TextView or EditText type of component. I cannot seem to find any tutorials online on how to do this and I'm not really sure what to even look for. I have several that I need to make but here is an example of one of them:
input_textbox.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_margin="5dp"
android:background="#drawable/bg_form_info"
android:layout_width="wrap_content"
android:layout_height="#dimen/form_info_height">
<TextView
android:id="#+id/label"
android:hint="#string/label"
android:textSize="#dimen/label_text_size"
android:visibility="visible"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/display"
android:hint="#string/display"
android:textSize="#dimen/form_info_text_size"
android:layout_alignParentBottom="true"
android:background="#android:color/transparent"
android:paddingLeft="#dimen/input_horizontal_padding"
android:paddingRight="#dimen/input_horizontal_padding"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageButton
android:id="#+id/error_icon"
android:contentDescription="#string/error"
android:src="#drawable/ic_error"
android:background="#android:color/transparent"
android:clickable="true"
android:focusable="false"
android:visibility="visible"
android:paddingRight="#dimen/input_horizontal_padding"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Textbox.java
public class Textbox extends [WHAT GOES HERE] {
TextView inputLabel;
EditText inputField;
ImageButton errorIcon;
String errorMessage;
public Textbox(Context context, String label) {
super(context);
init(label);
}
public Textbox(Context context, AttributeSet attrs) {
super(context, attrs);
init(""); // I don't know how to pass the label here
}
public Textbox(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(""); // or here
}
private void init(String label) {
inputLabel = findViewById(R.id.label); // How do I connect this class to the xml?
inputLabel.setText(label);
inputField = findViewById(R.id.input_field);
inputField.setHint(label);
inputField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
inputLabel.setVisibility((count > 0) ? View.VISIBLE : View.GONE);
}
#Override
public void afterTextChanged(Editable s) { }
});
errorIcon = findViewById(R.id.error_icon);
errorIcon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showErrorMessage();
}
});
}
public String getErrorMessage() {
return errorMessage;
}
public void showErrorMessage() {
showToast(getContext(), errorMessage);
}
public String getValue() {
return inputField.getText().toString();
}
public void setValue(String value) {
inputField.setText(value);
}
public void showErrorIcon(String errorMessage) {
this.errorMessage = errorMessage;
showErrorMessage();
errorIcon.setVisibility(VISIBLE);
}
public void hideErrorIcon() {
this.errorMessage = "";
errorIcon.setVisibility(GONE);
}
}
activity_main.xml
...
<com.example.application.inputs.Textbox
android:id="#+id/test_textbox"
android:layout_below="#id/end_date_display"
[HOW DO I ADD THE LABEL AND OTHER OPTIONS?]
android:layout_width="match_parent"
android:layout_height="wrap_content" />
...
Any help would be great or even a link to a Youtube video is better then nothing.
You can init your custom Textbox on Activity class like
public TextBox mTextBox = new TextBox(label)
add add it to the parent view.
If you want to set the label of the view in the xml,
add the public method in your custom class like
public void setTag(String input) {
inputLabel.setText(input)
}
and set the tag from the code.
public textBoxReferred = findViewById(R.id.test_testbox)
textBoxReferred.setText("THE TAG")
I have just created a demo project for learning and the MVVM and how to use the Mvvm in our project.
but I have found an error while running the project
error: cannot find symbol class ViewModel
error: package ViewModel does not exist
error: package ViewModel does not exist
error: package ViewModel does not exist
and here is my code
public class User extends BaseObservable {
String email,password;
boolean isDataValidate;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isDataValidate() {
return !TextUtils.isEmpty(getEmail())&& Patterns.EMAIL_ADDRESS.matcher(getEmail()).matches()&&
getPassword().length()>6;
}
public void setDataValidate(boolean dataValidate) {
isDataValidate = dataValidate;
}
}
and Here is my ViewModel class
public class LoginViewModel extends ViewModel {
private User user;
private LoginResultCallback loginResultCallback;
public LoginViewModel(LoginResultCallback loginResultCallback){
this.loginResultCallback=loginResultCallback;
this.user=new User();
}
public String getEmailText1(){
return user.getEmail();
}
public String getPasswordText1(){
return user.getPassword();
}
public TextWatcher getEmailText(){
return new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
user.setEmail(editable.toString());
}
};
}
public TextWatcher getPasswordText(){
return new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
user.setPassword(editable.toString());
}
};
}
public void onLoginClicked(View view)
{
if (user.isDataValidate()){
loginResultCallback.onSuccess("Login was Successfull");
}
else{
loginResultCallback.onError("Login Invalid Credential");
}
}
}
and here is my MainActivity
public class MainActivity extends AppCompatActivity implements LoginResultCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding activityMainBinding= DataBindingUtil.setContentView(this,R.layout.activity_main);
LoginViewModel loginViewModel=new LoginViewModel(this);
activityMainBinding.setViewModel(loginViewModel);
//activityMainBinding.setViewModel(ViewModelProviders.of(this,new LoginViewModelFactory(this)).get(LoginViewModel.class));
}
#Override
public void onSuccess(String Message) {
Toast.makeText(this, ""+Message, Toast.LENGTH_SHORT).show();
}
#Override
public void onError(String Error) {
Toast.makeText(this, ""+Error, Toast.LENGTH_SHORT).show();
}
}
and here is viewModelFactory class
public class LoginViewModelFactory extends ViewModelProvider.NewInstanceFactory {
private LoginResultCallback loginResultCallback;
public LoginViewModelFactory(LoginResultCallback loginResultCallback)
{
this.loginResultCallback=loginResultCallback;
}
#NonNull
#Override
public <T extends ViewModel> T create(#NonNull Class<T> modelClass) {
return (T) new LoginViewModel(loginResultCallback);
}
}
and XML is here
<?xml version="1.0" encoding="utf-8"?>
<data>
<variable
name="viewModel"
type="com.example.designinfpattern.ViewModel.LoginViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:addTextChangedListener="#{viewModel.emailText}"
android:hint="Enter Your account Email or Username"
/>
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Your account password"
app:addTextChangedListener="#{viewModel.passwordText}" />
</LinearLayout>
<Button
android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="#{viewModel::onLoginClicked}"
android:text="Login" />
</LinearLayout>
Here is the dependency which I am using on the build Gradle file:
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
I don't know how to solve this error and I'm doing R&D but not find a proper solution. Please help me out to solve the problem
thanks in advance
You need to rename the ViewModel folder (package) from ViewModel to viewmodel
Add the following in your build.gradle
// ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:2.1.0"
// alternatively - just ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:2.1.0"
Today, I faced the same problem in MVVM. I fixed this. Everything was working fine and suddenly I started getting this same error. Then I recall what changes I recently made. Then I realised I moved my Activity files from one Package to another after this I stared facing the problem. In layout, I changed my viewmodel packages accordingly and Bingo! Sharing this it may help and save time of others in case same thing happened in future.
When I try to set the onClick method in my Google's SignInButton:
android:onClick="#{() -> viewModel.onGoogleLoginClick()}"
I always get this error:
Found data binding errors.
****/ data binding error ****msg:Cannot find the proper callback class for android:onClick. Tried android.view.View but it has 0 abstract
methods, should have 1 abstract methods.
file:/Users/user/Android/project/app/src/main/res/layout/activity_login.xml loc:53:31 - 53:66 ****\ data binding error ****
Here is my code:
activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".ui.login.LoginActivity">
<data>
<import type="android.view.View" />
<variable
name="viewModel"
type="com.example.myapp.ui.login.LoginViewModel" />
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="#dimen/default_layout_padding">
<EditText
android:id="#+id/login_name_editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/login_username_hint"
android:inputType="text"
android:text="#{viewModel.mEmail}" />
<EditText
android:id="#+id/login_pass_editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/login_name_editText"
android:hint="#string/login_password_hint"
android:inputType="numberPassword"
android:text="#{viewModel.mPassword}" />
<Button
android:id="#+id/login_login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/login_pass_editText"
android:onClick="#{() -> viewModel.onServerLoginClick()}"
android:text="#string/login_login_button_text"
android:textAllCaps="true" />
<com.google.android.gms.common.SignInButton
android:id="#+id/login_google_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/login_login_button"
android:onClick="#{() -> viewModel.onGoogleLoginClick()}"/>
</RelativeLayout>
</layout>
LoginViewModel.class
public class LoginViewModel extends BaseViewModel<LoginNavigator> implements
GoogleApiClient.OnConnectionFailedListener, OnCompleteListener<GoogleSignInAccount>,
GoogleApiClient.ConnectionCallbacks {
private static final String LOG_TAG = LoginViewModel.class.getSimpleName();
public String mEmail;
public String mPassword;
public LoginViewModel(DataManager dataHelper, SchedulerProvider schedulerProviderHelper) {
super(dataHelper, schedulerProviderHelper);
}
public void onServerLoginClick() {
if (CommonUtils.loginDataIsCorrect(mEmail, mPassword)) {
doServerLogin(mEmail, mPassword);
} else {
getNavigator().handleError();
}
}
public void onGoogleLoginClick() {
getNavigator().googleLogin();
}
// Server
private void doServerLogin(String name, String pass) {
...
}
// Google
protected void doGoogleLogin(FragmentActivity fragmentActivity, Context context) {
...
}
...
}
LoginActivity.class
public class LoginActivity extends BaseActivity<ActivityLoginBinding, LoginViewModel> implements LoginNavigator {
private static final int REQUEST_CODE_REGISTER = 0;
private static final int REQUEST_CODE_GOOGLE_SIGN_IN = 1;
#BindString(R.string.login_data_missing_message)
String mDataMissingMessage;
#Inject
LoginViewModel mLoginViewModel;
private ActivityLoginBinding mActivityLoginBinding;
public static Intent newIntent(Context context) {
return new Intent(context, LoginActivity.class);
}
#Override
public int getBindingVariable() {
return BR.viewModel;
}
#Override
public int getLayoutId() {
return R.layout.activity_login;
}
#Override
public LoginViewModel getViewModel() {
return mLoginViewModel;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mActivityLoginBinding = getViewDataBinding();
mLoginViewModel.setNavigator(this);
mActivityLoginBinding.loginGoogleButton.setSize(SignInButton.SIZE_WIDE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_GOOGLE_SIGN_IN:
mLoginViewModel.handleGoogleSignInResult(data);
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void googleLogin() {
mLoginViewModel.doGoogleLogin(this, this);
}
#Override
public void showGoogleForm(GoogleApiClient googleApiClient) {
Intent googleIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(googleIntent, REQUEST_CODE_GOOGLE_SIGN_IN);
}
...
}
And the BaseActivity.class, where I bind view and data for each Activity:
public abstract class BaseActivity<T extends ViewDataBinding, V extends BaseViewModel> extends AppCompatActivity {
private T mViewDataBinding;
private V mViewModel;
public abstract int getBindingVariable();
#LayoutRes
public abstract int getLayoutId();
public T getViewDataBinding() {
return mViewDataBinding;
}
public abstract V getViewModel();
public void performDependencyInjection() {
AndroidInjection.inject(this);
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
performDependencyInjection();
super.onCreate(savedInstanceState);
performDataBinding();
}
#Override
protected void onResume() {
super.onResume();
}
private void performDataBinding() {
mViewDataBinding = DataBindingUtil.setContentView(this, getLayoutId());
this.mViewModel = mViewModel == null ? getViewModel() : mViewModel;
mViewDataBinding.setVariable(getBindingVariable(), mViewModel);
mViewDataBinding.executePendingBindings();
}
}
Does anyone know why this error? Because SignInButton implements OnClickListener. I have tried Invalidate Caches / Restart and deleting .gradle and .idea folders but is still not working.
Luckily, we've got #BindingAdapter to solve issues similar to this. Here's an example in Kotlin:
BindingAdapters.kt
#BindingAdapter("android:onClick")
fun bindSignInClick(button: SignInButton, method: () -> Unit) {
button.setOnClickListener { method.invoke() }
}
layout.xml
<com.google.android.gms.common.SignInButton
...
android:onClick="#{() -> viewModel.onSignInClick()}" />
It's a interesting question, since SignInButton extends View, but the doc states explicitly to register a listener with setOnClickListener(OnClickListener) in the class and not in the xml. Databinding wraps up the lamda expression as a listener (you can see that in the auto-generated data binding class) and probably it doesn't stick with the listener, which SignInButton is expecting. E.g. if you try to pass a View.OnClickListener variable via xml, you shouldn't get that compile error, but you probably also won't be able to receive your click events (like it's stated in the doc).
I have implemented the new Android data-binding, and after implementing realised that it does not support two-way binding. I have tried to solve this manually but I am struggling to find a good solution to use when binding to an EditText.
In my layout I have this view:
<EditText
android:id="#+id/firstname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapWords|textNoSuggestions"
android:text="#{statement.firstName}"/>
Another view is also showing the results:
<TextView
style="#style/Text.Large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{statement.firstName}"/>
In my fragment I create the binding like this:
FragmentStatementPersonaliaBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_statement_personalia, container, false);
binding.setStatement(mCurrentStatement);
This works and puts the current value of firstName in the EditText. The problem is how to update the model when the text changes. I tried putting an OnTextChanged-listener on the editText and updating the model. This created a loop killing my app (model-update updates the GUI, which calls textChanged times infinity). Next I tried to only notify when real changes occured like this:
#Bindable
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
boolean changed = !TextUtils.equals(this.firstName, firstName);
this.firstName = firstName;
if(changed) {
notifyPropertyChanged(BR.firstName);
}
}
This worked better, but everytime I write a letter, the GUI is updated and for som reason the edit-cursor is moved to the front.
Any suggestions would be welcome
EDIT 04.05.16:
Android Data binding now supports two way-binding automatically!
Simply replace:
android:text="#{viewModel.address}"
with:
android:text="#={viewModel.address}"
in an EditText for instance and you get two-way binding. Make sure you update to the latest version of Android Studio/gradle/build-tools to enable this.
(PREVIOUS ANSWER):
I tried Bhavdip Pathar's solution, but this failed to update other views I had bound to the same variable. I solved this a different way, by creating my own EditText:
public class BindableEditText extends EditText{
public BindableEditText(Context context) {
super(context);
}
public BindableEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BindableEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private boolean isInititalized = false;
#Override
public void setText(CharSequence text, BufferType type) {
//Initialization
if(!isInititalized){
super.setText(text, type);
if(type == BufferType.EDITABLE){
isInititalized = true;
}
return;
}
//No change
if(TextUtils.equals(getText(), text)){
return;
}
//Change
int prevCaretPosition = getSelectionEnd();
super.setText(text, type);
setSelection(prevCaretPosition);
}}
With this solution you can update the model any way you want (TextWatcher, OnTextChangedListener etc), and it takes care of the infinite update loop for you. With this solution the model-setter can be implemented simply as:
public void setFirstName(String firstName) {
this.firstName = firstName;
notifyPropertyChanged(BR.firstName);
}
This puts less code in the model-class (you can keep the listeners in your Fragment).
I would appreciate any comments, improvements or other/better solutions to my problem
This is now supported in Android Studio 2.1+ when using the gradle plugin 2.1+
Simply change the EditText's text attribute from #{} to #={} like this:
<EditText
android:id="#+id/firstname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapWords|textNoSuggestions"
android:text="#={statement.firstName}"/>
for more info, see: https://halfthought.wordpress.com/2016/03/23/2-way-data-binding-on-android/
#Gober The android data-binding support the two way binding. Therefore you do not need to make it manually. As you tried by putting the OnTextChanged-listener on the editText. It should update the model.
I tried putting an OnTextChanged-listener on the editText and updating
the model. This created a loop killing my app (model-update updates
the GUI, which calls textChanged times infinity).
It’s worth noting that binding frameworks that implement two-way binding would normally do this check for you…
Here’s the example of modified view model, which does not raise a data binding notification if the change originated in the watcher:
Let’s create a SimpleTextWatcher that only requires only one method to be overridden:
public abstract class SimpleTextWatcher implements TextWatcher {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
onTextChanged(s.toString());
}
public abstract void onTextChanged(String newValue);
}
Next, in the view model we can create a method that exposes the watcher. The watcher will be configured to pass the changed value of the control to the view model:
#Bindable
public TextWatcher getOnUsernameChanged() {
return new SimpleTextWatcher() {
#Override
public void onTextChanged(String newValue) {
setUsername(newValue);
}
};
}
Finally, in the view we can bind the watcher to the EditText using addTextChangeListener:
<!-- most attributes removed -->
<EditText
android:id="#+id/input_username"
android:addTextChangedListener="#{viewModel.onUsernameChanged}"/>
Here is the implementation of the view Model that resolve the notification infinity.
public class LoginViewModel extends BaseObservable {
private String username;
private String password;
private boolean isInNotification = false;
private Command loginCommand;
public LoginViewModel(){
loginCommand = new Command() {
#Override
public void onExecute() {
Log.d("db", String.format("username=%s;password=%s", username, password));
}
};
}
#Bindable
public String getUsername() {
return this.username;
}
#Bindable
public String getPassword() {
return this.password;
}
public Command getLoginCommand() { return loginCommand; }
public void setUsername(String username) {
this.username = username;
if (!isInNotification)
notifyPropertyChanged(com.petermajor.databinding.BR.username);
}
public void setPassword(String password) {
this.password = password;
if (!isInNotification)
notifyPropertyChanged(com.petermajor.databinding.BR.password);
}
#Bindable
public TextWatcher getOnUsernameChanged() {
return new SimpleTextWatcher() {
#Override
public void onTextChanged(String newValue) {
isInNotification = true;
setUsername(newValue);
isInNotification = false;
}
};
}
#Bindable
public TextWatcher getOnPasswordChanged() {
return new SimpleTextWatcher() {
#Override
public void onTextChanged(String newValue) {
isInNotification = true;
setPassword(newValue);
isInNotification = false;
}
};
}
}
I hope this is what you are looking and sure can help you. Thanks
There is a simpler solution. Just avoid updating field if it hadn't really changed.
#Bindable
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
if(this.firstName.equals(firstName))
return;
this.firstName = firstName;
notifyPropertyChanged(BR.firstName);
}
POJO:
public class User {
public final ObservableField<String> firstName =
new ObservableField<>();
public final ObservableField<String> lastName =
new ObservableField<>();
public User(String firstName, String lastName) {
this.firstName.set(firstName);
this.lastName.set(lastName);
}
public TextWatcherAdapter firstNameWatcher = new TextWatcherAdapter(firstName);
public TextWatcherAdapter lastNameWatcher = new TextWatcherAdapter(lastName);
}
Layout:
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{user.firstName, default=First_NAME}"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{user.lastName, default=LAST_NAME}"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editFirstName"
android:text="#{user.firstNameWatcher.value}"
android:addTextChangedListener="#{user.firstNameWatcher}"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editLastName"
android:text="#{user.lastNameWatcher.value}"
android:addTextChangedListener="#{user.lastNameWatcher}"/>
Watcher:
public class TextWatcherAdapter implements TextWatcher {
public final ObservableField<String> value =
new ObservableField<>();
private final ObservableField<String> field;
private boolean isInEditMode = false;
public TextWatcherAdapter(ObservableField<String> f) {
this.field = f;
field.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback(){
#Override
public void onPropertyChanged(Observable sender, int propertyId) {
if (isInEditMode){
return;
}
value.set(field.get());
}
});
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
}
#Override public void afterTextChanged(Editable s) {
if (!Objects.equals(field.get(), s.toString())) {
isInEditMode = true;
field.set(s.toString());
isInEditMode = false;
}
}
}
I struggled to find a full example of 2-way databinding. I hope this helps.
The full documentation is here:
https://developer.android.com/topic/libraries/data-binding/index.html
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="item"
type="com.example.abc.twowaydatabinding.Item" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#={item.name}"
android:textSize="20sp" />
<Switch
android:id="#+id/switch_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="#={item.checked}" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="change"
android:onClick="button_onClick"/>
</LinearLayout>
</layout>
Item.java:
import android.databinding.BaseObservable;
import android.databinding.Bindable;
public class Item extends BaseObservable {
private String name;
private Boolean checked;
#Bindable
public String getName() {
return this.name;
}
#Bindable
public Boolean getChecked() {
return this.checked;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}
public void setChecked(Boolean checked) {
this.checked = checked;
notifyPropertyChanged(BR.checked);
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
public Item item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
item = new Item();
item.setChecked(true);
item.setName("a");
/* By default, a Binding class will be generated based on the name of the layout file,
converting it to Pascal case and suffixing “Binding” to it.
The above layout file was activity_main.xml so the generate class was ActivityMainBinding */
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setItem(item);
}
public void button_onClick(View v) {
item.setChecked(!item.getChecked());
item.setName(item.getName() + "a");
}
}
build.gradle:
android {
...
dataBinding{
enabled=true
}
}