When some text is typed into the box for text, we can do certain operations depending on the value of the text. For this app, we will enable or disable the button to generate the QR code depending on whether the text input is an empty string or not. This behaviour will be done by use a TextWatcher . Inside MainActivity.java, create a final instance of TextWatcher as shown below:
The task of textWatcher is simple: When the text of the widget being ‘watched’ has been changed, two methods will be invoked: setText and updateGenerateButton. Add the methods to the MainActivity.java file:
setText ensures that the data member variable is set to a trimmed non-null string and then saves the string to SharedPreferences using the PreferenceHelper we defined earlier in this tutorial. Add the following member variables to the MainActivity class:
Next, the updateGenerateButton method will enable or disable the generateButton` depending on whether data is empty or not:
At this point, the textWatcher member variable is not yet being used. To have it do its work, we should have it watch for changes that happen to the editText widget. In the setListeners method, add the following line:
Now the app will watch the text that the user types in, trims the text of any whitespaces, and then enables or disables the generateButton depending on whether the trimmed text is empty or not.
You can check the complete code for the MainActivity.java file on github .