Help us understand the problem. What is going on with this article?

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

環境

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 ->
    }
)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away