By Alvin Alexander. Last updated: November 16, 2018
I’ve been working through the examples in the excellent Android book, Android Programming: The Big Nerd Ranch Guide, and was trying to figure out how the example in Chapter 10 worked, specifically how the crime data was being saved without the use of a “save” button. The code below shows that they use a combination of an addTextChangedListener
and a TextWatcher
(android.text.TextWatcher). I highlighted a few of the important parts:
mTitleField = (EditText)v.findViewById(R.id.crime_title); mTitleField.setText(mCrime.getTitle()); mTitleField.addTextChangedListener(new TextWatcher() { // the user's changes are saved here public void onTextChanged(CharSequence c, int start, int before, int count) { mCrime.setTitle(c.toString()); } public void beforeTextChanged(CharSequence c, int start, int count, int after) { // this space intentionally left blank } public void afterTextChanged(Editable c) { // this one too } });
They do a similar thing later in the code with a CheckBox
:
mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved); mSolvedCheckBox.setChecked(mCrime.isSolved()); mSolvedCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { // checkbox changes are saved here public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // set the crime's solved property mCrime.setSolved(isChecked); } });
I’m not sure that it’s a good idea to use this technique too often, but when you want/need to save a change to an EditText
or CheckBox
widget in an Android app without using a save button, these examples are helpful.