LoginSignup
20
13

More than 3 years have passed since last update.

EditText.addTextChangedListenerに便利な拡張関数が追加されていました

Posted at

環境

build.gradle
implementation 'androidx.core:core-ktx:1.1.0'

EditTextの入力中文字列を取得する時に使うTextWatcherは3つのコールバック関数をもつインターフェースです。

editText.addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
    }

    override fun afterTextChanged(s: Editable?) {
    }
})
コールバック 説明
beforeTextChanged テキストが編集される前に発生するイベント
onTextChanged テキストが変更された直後(日本語IMEの変換候補が出ている間も含む)
afterTextChanged テキストが変更された直後(入力が確定された後)

なのでほとんどのケースにおいてonTextChangedのみで良いです。しかし3つのコールバックがあるとKotlinではSAMが効かないので毎回冗長なコールバックを書かなければなりません。

core-ktxに各コールバックを単体でリッスンできる拡張関数が追加されました。

editText.doOnTextChanged { text, start, count, after -> 
}

非常に楽になりました🎉

そのほかの拡張関数と従来のaddTextChangedListenerをラムダ式で書ける拡張関数はこちらです。

editText.doBeforeTextChanged { text, start, count, after -> 
}

editText.doAfterTextChanged { text ->
}

editText.addTextChangedListener(
    beforeTextChanged = { text, start, count, after ->
    },
    onTextChanged = { text, start, count, after ->
    },
    afterTextChanged = { text ->
    }
)
20
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
13