Two-way Databinding with RxJava - android

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.

Related

How to mock an EditText in android using Mockito

I am trying to write a Unit Test for a validator of my android Application. The validator accepts as parameter EditText, therefore I need to mock it. However the mocking does not work, forcing the Test to crash on calling the when() method with the exception:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
My code is:
#RunWith(MockitoJUnitRunner.class)
public class MyUnitTest
{
#Mock
Context mMockContext;
#Test
public void validateIsCorrect() {
final EditText input = Mockito.mock(EditText.class);
when(input.getText()).thenReturn(Editable.Factory.getInstance().newEditable("123"));
...
}
}
The dependencies in build.gradle file are:
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.10.19'
The method getText() of the EditText is not private or final. What am I doing wrong? Is it possible to mock an EditText this way? How?
When you're running a unit test, you're using a standard JVM context, not Android's context and that's why it's crashing: The Editable.Factory class and it's methods (like getInstance()) are not in the classpath. And they have not been mocked either.
What I'd do is to create a class that implements Editable with a private member to hold a string reference and use it to mock the getText() method.
Something like this:
class MockEditable implements Editable {
private String str;
public MockEditable(String str) {
this.str = str;
}
#Override #NonNull
public String toString() {
return str;
}
#Override
public int length() {
return str.length();
}
#Override
public char charAt(int i) {
return str.charAt(i);
}
#Override
public CharSequence subSequence(int i, int i1) {
return str.subSequence(i, i1);
}
#Override
public Editable replace(int i, int i1, CharSequence charSequence, int i2, int i3) {
return this;
}
#Override
public Editable replace(int i, int i1, CharSequence charSequence) {
return this;
}
#Override
public Editable insert(int i, CharSequence charSequence, int i1, int i2) {
return this;
}
#Override
public Editable insert(int i, CharSequence charSequence) {
return this;
}
#Override
public Editable delete(int i, int i1) {
return this;
}
#Override
public Editable append(CharSequence charSequence) {
return this;
}
#Override
public Editable append(CharSequence charSequence, int i, int i1) {
return this;
}
#Override
public Editable append(char c) {
return this;
}
#Override
public void clear() {
}
#Override
public void clearSpans() {
}
#Override
public void setFilters(InputFilter[] inputFilters) {
}
#Override
public InputFilter[] getFilters() {
return new InputFilter[0];
}
#Override
public void getChars(int i, int i1, char[] chars, int i2) {
}
#Override
public void setSpan(Object o, int i, int i1, int i2) {
}
#Override
public void removeSpan(Object o) {
}
#Override
public <T> T[] getSpans(int i, int i1, Class<T> aClass) {
return null;
}
#Override
public int getSpanStart(Object o) {
return 0;
}
#Override
public int getSpanEnd(Object o) {
return 0;
}
#Override
public int getSpanFlags(Object o) {
return 0;
}
#Override
public int nextSpanTransition(int i, int i1, Class aClass) {
return 0;
}
}
You can then make use of this class
Mockito.when(input.getText()).thenReturn(new MockEditable("123"));
Looking at this from a bit further away; I am asking myself: why does your validator need to know anything about Android specific classes?
What I mean is: I assume that your validator (in the end) has to check the properties of maybe a String, or something alike?
I would thus suggest to focus on separating concerns here:
Create a component that fetches a String from your EditText
Create a validator that works with such strings
Then you don't need any specific mocking for your validator in the first place!
final EditText editText = Mockito.mock(EditText.class);
final ArgumentCaptor<Editable> captor = ArgumentCaptor.forClass(Editable.class);
Mockito.doNothing().when(editText).setText(captor.capture());
Mockito.when(editText.getText()).thenAnswer(new Answer<Object>() {
#Override
public Object answer(InvocationOnMock invocation) {
return captor.getValue();
}
});
What about this guys, it works for me:
Please don't forget to add the MockitoAnnotations.init(this); and also use
#Mock private EditTextView passwordField;
#Before
public void init() {
MockitoAnnotations.initMocks(this);
when(rootView.findViewById(R.id.button_logout)).thenReturn(buttonLogout);
when(rootView.findViewById(R.id.button_unlock)).thenReturn(buttonUnlock);
when(rootView.findViewById(R.id.ScreenLock_PasswordTextField)).thenReturn(passwordField);
when(passwordField.getText()).thenReturn(Editable.Factory.getInstance().newEditable("asd"));
when(application.getPassword()).thenReturn("asd");
sut = new ScreenLockPresenterImpl(application, rootView, screenLockListener,
logoutButtonClickListener);
}
#Test
public void testOnClickWhenOk() {
sut.onClick(null);
verify(passwordField).getText();
verify(screenLockListener).unLock();
}
I think this is what you are looking for:
when(passwordField.getText()).thenReturn(Editable.Factory.getInstance().newEditable("asd"));

Xamarin android format string onkey pressed

I have this EditText in which I want the user to type a credit card number, so I want to format the string while the user is typing it, I specifically want the string to have a space every 4 numbers, like this:
xxxx xxxx xxxx xxxx
I found that I could use TextWatcher and onKeyUp but I couldn't understand how use it in a EditText, if some one could explain me I would really appreciate it, thanks.
Create a class that implements the ITextWatcher interface. Then add an instance of that class as a text changed listener...
public class CreditCardFormatter : Java.Lang.Object, ITextWatcher
{
private EditText _editText;
public CreditCardFormatter(EditText editText)
{
_editText = editText;
}
public void AfterTextChanged(IEditable s)
{
}
public void BeforeTextChanged(ICharSequence s, int start, int count, int after)
{
}
public void OnTextChanged(ICharSequence s, int start, int before, int count)
{
}
}
In your activity.. (or OnCreateView in a fragment)
public override void OnCreate()
{
// other code..
myEditText.AddTextChangedListener(new CreditCardFormatter(myEditText));
}
Then use the override methods to reformat the text to show what you need.

Common TextWatcher class

I have 8 fragments, each inflating a layout with among others, an EditText wrapped inside a TextInputLayout. In the onCreateView, am implementing
EditText inputTextFrag1 = (EditText)findViewById(R.id.et_frag1);
inputTextFrag1.addTextChangedListener(new MyTextWatcher(inputTextFrag1));
Am also having to implement MyTextWatcher class in each fragment body as below:
private class MyTextWatcher implements TextWatcher {
private View view;
public MyTextWatcher(View view) {
this.view = view;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
saveButton.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
saveButton.setClickable(false);
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
saveButton.getBackground().setColorFilter(null);
switch (view.getId()) {
case R.id.et_frag1:
validateName();
break;
}
}
}
Where validateName();
private boolean validateName() {
if (inputTextFrag1 .getText().toString().trim().isEmpty()) {
mInputLayoutName.setError(getString(R.string.err_msg_name));
requestFocus(inputTextFrag1 );
return false;
} else {
mInputLayoutName.setErrorEnabled(false);
}
return true;
}
Is there a way to have just one MyTextWatcher class somewhere and one validateName() method to be called by each fragment instead of duplicating the same class/method 8 times. Thanks
Is this the correct way to place the TextWatcher class inside a BaseDialogFragment?
public abstract class BaseDialogFragment extends DialogFragment{
private class MyTextWatcher implements TextWatcher {
private View view;
public MyTextWatcher(View view) {
this.view = view;
}
#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) {
}
}
}
What logic goes into the beforeTextChanged and afterTextChanged methods of the TextWatcher?
You can create a BaseFragment that will be extended by your fragments.
Therefore, you can manage your TextWatcher inside this BaseFragment and consequently the fragments which have this heritage, will receive your expected logic.
As in the following example:
BaseFragment.class
public abstract class BaseFragment extends Fragment implements TextWatcher {
EditText editText;
Button button;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//inflate your edit text
...
//inflate your button
...
editText.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//text watcher listener
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//text watcher listener
}
#Override
public void afterTextChanged(Editable s) {
//text watcher listener
}
}
YourFragment.class
public class YourFragment extends BaseFragment {
...
}
No need for duplication. In your current implementation, it seems your MyTextWatcher class is an inner class of another class (probably fragment class). In this way of implementation you can't share it among all fragment classes.
However if you define your MyTextWatcher class as a standalone class, you can then use it for all fragment classes. To do this, you should only be using the variables and class members that have been declared in scope of the class being defined. In your case saveButton variable doesn't belong to MyTextWatcher class (it's accessible from the outer scope), in such cases, you should import them via the constructor method.
private class MyTextWatcher implements TextWatcher {
private View view;
private Button saveButton;
public MyTextWatcher(View view, Button saveButton) {
this.view = view;
this.saveButton = saveButton;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
saveButton.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
saveButton.setClickable(false);
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
saveButton.getBackground().setColorFilter(null);
switch (view.getId()) {
case R.id.et_frag1:
validateName();
break;
}
}
}
You can now instantiate this class 8 times for your 8 fragments.
However, #Bruno Vieira's solution is better (i.e. using a base fragment class).

Does android View reference passed to outside class create memory leak?

i have a question. Does class like this:
public class AmountTextWatcher implements TextWatcher {
private final TextView amountTo;
public AmountTextWatcher(TextView amountTo) {
this.amountTo = amountTo;
}
#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) {
Pattern mPattern = Pattern.compile(PatternHolder.amountPattern());
Matcher matcher = mPattern.matcher(s.toString());
if (matcher.find()) {
amountTo.setTextColor(Color.BLACK);
} else {
amountTo.setTextColor(Color.RED);
if (s.length() > 0) s.delete(s.length() - 1, s.length());
}
}
}
create a memory leak? do i need to hold a reference to such to it and clear it in onDestroy (or onDestroyView, whatever).
cheers
Wojtek
Your AmountTextWatcher is held by a TextView. The AmountTextWatcher holds onto the same TextView. Hence, these two objects, from a garbage collection standpoint, are part of the same object graph. The lifespan of those objects will be determined by who holds onto either of them.
If your only reference to the AmountTextWatcher is from the TextView, then the AmountTextWatcher will live as long as the TextView does. Normally, that will be as long as the activity that is showing the TextView lives.
IOW, your AmountTextWatcher will not be a memory leak, so long as the TextView it is associated with is not itself leaked.

Create two-way binding with Android Data Binding

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
}
}

Categories

Resources