Download Teach Yourself Android Application Development in 24

Transcript
Using Common Form Controls
Committing EditText Input
To handle EditText input to a form, you need to determine when new text has
been entered. To do this, you can listen for EditText key events and commit the
text entered when certain keys are pressed. For example, to listen for the Enter key
during input of the Nickname setting, you would register View.OnKeyListener by
using the setOnKeyListener() method of the EditText control, as follows:
final EditText nicknameText =
(EditText) findViewById(R.id.EditText_Nickname);
nicknameText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
String strNicknameToSave = nicknameText.getText().toString();
// TODO: Save Nickname setting (strNicknameToSave)
return true;
}
return false;
}
});
Listening for EditText Keystrokes
Eventually, you will design a Password dialog. Say that you want to match the text
strings within two EditText password fields, called EditText_Pwd1 and
EditText_Pwd2, while the user is typing. A third TextView control, called
TextView_PwdProblem, provides feedback about whether the passwords match.
First, you need to retrieve each of the controls:
final EditText p1 = (EditText) findViewById(R.id.EditText_Pwd1);
final EditText p2 = (EditText) findViewById(R.id.EditText_Pwd2);
final TextView error = (TextView) findViewById(R.id.TextView_PwdProblem);
Next, you add TextWatcher to the second EditText control, using the
addTextChangedListener() method, like this:
p2.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
String strPass1 = p1.getText().toString();
String strPass2 = p2.getText().toString();
if (strPass1.equals(strPass2)) {
error.setText(R.string.settings_pwd_equal);
} else {
error.setText(R.string.settings_pwd_not_equal);
}
}
// Other required overrides do nothing
});
169