android EditTextの入力内容をリアルタイムで取得する TextWatcher
今回は、androidで、EditTextの入力内容をリアルタイムで取得する方法を書きます。
リアルタイムで取得するには、TextWatcherというものを使います。
導入も簡単です。
このような形で、書きます↓
public class MainActivity extends Activity implements TextWatcher { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EditText edittext = (EditText)findViewById(R.id.edittext); edittext.addTextChangedListener(this); //追加 } /*--- 追加 ---*/ @Override public void beforeTextChanged(CharSequence s, int start, int count,int after) { //操作前のEtidTextの状態を取得する } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { //操作中のEtidTextの状態を取得する } @Override public void afterTextChanged(Editable s) { //操作後のEtidTextの状態を取得する /*--- 取得例(EditTextの更新内容をTextViewに反映) ---*/ TextView textView = (TextView)findViewById(R.id.textview); textView.setText(s.toString()); /*--- 取得例 ---*/ } /*--- 追加 ---*/ }
<EditText android:id="@+id/edittext" android:layout_width="fill_parent" android:layout_height="wrap_content" />
追加すのは、
- 「 implements TextWatcher」,
- 「.addTextChangedListener(this); 」,
- 「beforeTextChanged(CharSequence s, int start, int count,int after)」
- 「onTextChanged(CharSequence s, int start, int before, int count) 」
- 「afterTextChanged(Editable s)」
です。
ちなみに、上のプログラムは、EditTextの更新内容をリアルタイムにTextViewに反映するものです。
ここからは、「beforeTextChanged(CharSequence s, int start, int count,int after)」辺りを少し解説します。
- 「beforeTextChanged・・・」
こちらは、操作前のEtidTextの状態を取得できます。
ただし、削除や数字の入力などは最新の情報は取得されません。
引数は、s, start, count, afterとあります。
第1引数は、入力された文字です。
第2引数は、新たに追加された文字列の位置です。(0から始まります)
第3引数は、新たに文字列を入力する事によって、変更された総文字列の数です。
第4引数は、新たに追加された文字列の数です。
例えば、
「aaa」という文字が入力されています。
↓
「aaa」に「v」を追加しました。
この「aaa」→「aaav」になったときの引数の値はこれです↓
- 「onTextChanged・・・」
操作中のEtidTextの状態を取得できます。
リアルタイムの文字取得ができます。他には、リアルタイムの入力文字数などの制御とか。
引数は、s, start, before, countとあります。
第1引数は、入力された文字です。
第2引数は、新たに追加された文字列の位置です。(0から始まります)
第3引数は、削除される既存文字列の数です。
第4引数は、新たに追加された文字列の数です。
例えば、
「aaa」という文字が入力されています。
↓
「aaa」に「v」を追加しました。
この「aaa」→「aaav」になったときの引数の値はこれです↓
- 「afterTextChanged・・・」
操作後のEtidTextの状態を取得できます。
リアルタイムの文字取得ができます。
普通にリアルタイムの文字取得がしたいなら、afterの方が使いやすいです。
引数の「s」には、変更された文字列が入っています。
以上で、終わります。
参考サイト
TextWatcherでEditTextの入力内容をリアルタイムに反映する | GE Android Blog