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

フォーム入力画面のバリデーションタイミング

0
Posted at

Androidのフォーム入力画面でバリデーションをかけるタイミングをメモします。

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?) {
        validationCheck()
    }
})

1つ目はafterTextChangedです。テキストが入力されるたびにバリデーションを行うと入力直後の状態を正しく保つことができUIへの即時反映が可能です。だたしバリデーション処理が重いと返って端末に負荷がかかるのでEditText自身の文字制限などのテキストチェックのみ行います。

editText.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        validationCheck()
        true
    } else {
        false
    }
}

2つ目はsetOnEditorActionListenerです。文字を打ってEditTextから離れたタイミングで処理が走るので、一番正確なバリデーションタイミングです。addTextChangedListenerと比べ連続で処理されることはないので、テキストチェックの他にフォーム全体のバリデーションチェックにも使えます。

sbmitButton.setOnClickListener {
  if (checkInput()) {
    return@setOnClickListener
  }
  submit()
}

3つ目は決定ボタンにてバリデーションチェックを行います。こちらも正確ですがフォームの入力量が多いとどこでエラーになったのか分かりにくいのでエラー後のメッセージ処理は気を付ける必要があります。

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