2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Android】TextWatcherでEditTextの入力を監視する【Kotlin】

Posted at

TextWatcher

監視したいEditTextがあるクラスにTextWatcherクラスを継承することで、以下の三つのクラスを使ってそれぞれのタイミングでEditTextに変化が起きた時を冠することができます。
beforeTextChanged

クラス タイミング
beforeTextChanged 変化が起きる直前
onTextChanged 変化が起きた時
afterTextChanged 変化が起きた後

余談ですが、3つのタイミングがありますが 細かく監視をしたい時以外はどれか一つ(afterTextChangedだけ)で問題ないと思います。
なので、TextWatcherを継承したinterfaceを使うことでもっと簡単に書くことができるみたいです。

実践

class MainActivity : AppCompatActivity(),TextWatcher {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val editText = findViewById<EditText>(R.id.edit_text)
        editText.addTextChangedListener(this)
// addTextChangedListenerないと監視が始まらないので注意

    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

    }

    override fun afterTextChanged(p0: Editable?) {
        Toast.makeText(this,"変化後", LENGTH_LONG).show()
    }

参考

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?