例えば AlertDialog でテキストを入力するようにして、未入力のときはボタンを押せないようにしたいとします。
AlertDialog の getButton() で Button インスタンスが取れるのでこれを利用します。
取得するボタンは BUTTON_POSITIVE, BUTTON_NEGATIVE, BUTTON_NEUTRAL で指定します。
あとは EditText に TextWatcher を追加して、テキストの変更時にボタンの isEnabled を変更します。
初回時 EditText が空ならボタンを disabled にしておかないといけません。
AlertDialog の getButton() は show() の前に呼ぶと NPE になるので注意が必要です。
val editText = EditText(this).apply {
inputType = InputType.TYPE_CLASS_TEXT
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT
).apply {
val margin = (16 * resources.displayMetrics.density).toInt()
marginStart = margin
marginEnd = margin
}
}
val frameLayout = FrameLayout(this).apply {
addView(editText)
}
val dialog = AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Message")
.setView(frameLayout)
.setPositiveButton(android.R.string.ok, null)
.create()
editText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = !s.isNullOrBlank()
}
})
dialog.show()
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false

