
android EditText 文字が変更された時、変更を検知するサンプル@tryEditText00


android EditText 文字が変更を検知する。
大事なところ
addTextChangedListenerでリスナーをセットする。
beforeTextChanged→onTextChanged→afterTextChanged
の順番に呼ばれる。
beforeTextChangedは入力前の値が入ってる
onTextChangedの段階で値はもう変化してる。
関連項目
android.text.TextWatcher
addTextChangedListener
開発環境
Eclipse IDE バージョン: 3.7 Indigo Service Release 1
ターゲットプラットフォーム: 2.1
API レベル: 7
package trial.sample.tryedittext00; import android.app.Activity; import android.os.Bundle; import android.widget.EditText; import android.text.Editable; import android.text.TextWatcher; // TextWatcherのためのimport import android.util.Log; public class TryEditText00Activity extends Activity { private EditText mEditText; // 変更を検知するエディットボックス @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // リスナーを仕込むエディットボックス this.mEditText = (EditText)this.findViewById(R.id.editText1); this.mEditText.addTextChangedListener( new TextWatcherCustom( (EditText)this.findViewById(R.id.editText2))); } } //////////////////////////////////////////////////////////// // テキストの変更を検知するために必要 // 匿名クラスとして直接addTextChangedListenerのとこに書いてもいい class TextWatcherCustom implements TextWatcher { // 通知するためのエディットボックス private final EditText mNotifyEditText; // コンストラクタ public TextWatcherCustom(final EditText notifyEditText) { this.mNotifyEditText = notifyEditText; } //////////////////////////////////////////////////////////// // テキスト変更後 public void afterTextChanged(Editable s) { Log.v(TextWatcher.class.getSimpleName(), "afterTextChanged s: " + s.toString()); } //////////////////////////////////////////////////////////// // テキスト変更前 public void beforeTextChanged(CharSequence s, int start, int count, int after) { Log.v(TextWatcher.class.getSimpleName(), "beforeTextChanged s:" + s.toString()); } //////////////////////////////////////////////////////////// // テキスト変更後 public void onTextChanged(CharSequence s, int start, int before, int count) { Log.v(TextWatcher.class.getSimpleName(), "onTextChanged s: " + s.toString()); this.mNotifyEditText.setText(s); } }
Androidのmain.xmlをいじってEditText内の右端に固定の文字を表示するサン... android EditText で入力されたEditTextを識別するサンプル@tryTextWatche...