Adding TextWatcher on EditText using Rxjava and RxBinding
In this tutorial we will be adding TextWatcher on an EditText using RxBinding. RxBinding is a set of libraries that allow you to react to user interface events via the RxJava paradigm . This post is included in series of post which will cover RxJava in detail.
But why ?
First of all we need a reason for this change.
- And the reason is great simplification of the watcher which will provide only the changed text which is needed in most of the cases.
- Also we can also hook RxJava operators to the stream to manipulate the output.
- Reduction in code boilerplate code.
- Also its cool.. \m/
Lets start coding
First of all you have to add support for RxJava in your gradle file as explained in this tutorial. We are using lambda expression in this tutorial for code clarity, so you should setup that also from our tutorial. Also need to add RxBindings to app/build.gradle file
1 |
compile 'com.jakewharton.rxbinding:rxbinding:1.0.0' |
Now we are ready to use RxJava with Lambda expression and RxBindings.
In this code we are watching a EditText for text change and then just displaying same text in TextView below it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class RxBindingTextWatcherDemo extends BaseFragment { @BindView(R.id.textView) TextView textView; @BindView(R.id.etTextListener) EditText editText; @Override public int setLayout() { return R.layout.fragment_et_listener; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setupRxListener(); } //-------------------Main logic here-------------------// private void setupRxListener() { RxTextView.textChanges(editText).subscribe(text -> { textView.setText(text); }); } } |
This is all we need to do for this example. If we will not be using RxBinding then we have to write a lot of code for this same task. Example code for raw TextWatcher is shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
private void setupSimpleListener() { editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { textView.setText(s); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { } }); } |
This same functionality will take 16 lines which can be don in 3 lines using Rxjava RxBinding.
Please comment for any queries.