2018年9月15日土曜日

AlertDialog の Button の有効/無効を切り替える

AlertDialog の PositiveButton, NegativeButton, NeutralButton では、listener での実装によらずタップしたときに必ずダイアログが閉じます。

例えば AlertDialog でテキストを入力するようにして、未入力のときはボタンを押せないようにしたいとします。

AlertDialog の getButton() で Button インスタンスが取れるのでこれを利用します。
取得するボタンは BUTTON_POSITIVE, BUTTON_NEGATIVE, BUTTON_NEUTRAL で指定します。

あとは EditText に TextWatcher を追加して、テキストの変更時にボタンの isEnabled を変更します。

初回時 EditText が空ならボタンを disabled にしておかないといけません。
AlertDialog の getButton() は show() の前に呼ぶと NPE になるので注意が必要です。
  1. val editText = EditText(this).apply {  
  2.     inputType = InputType.TYPE_CLASS_TEXT  
  3.     layoutParams = FrameLayout.LayoutParams(  
  4.         FrameLayout.LayoutParams.MATCH_PARENT,  
  5.         FrameLayout.LayoutParams.WRAP_CONTENT  
  6.     ).apply {  
  7.         val margin = (16 * resources.displayMetrics.density).toInt()  
  8.         marginStart = margin  
  9.         marginEnd = margin  
  10.     }  
  11. }  
  12.   
  13. val frameLayout = FrameLayout(this).apply {  
  14.     addView(editText)  
  15. }  
  16.   
  17. val dialog = AlertDialog.Builder(this)  
  18.     .setTitle("Title")  
  19.     .setMessage("Message")  
  20.     .setView(frameLayout)  
  21.     .setPositiveButton(android.R.string.ok, null)  
  22.     .create()  
  23.   
  24. editText.addTextChangedListener(object : TextWatcher {  
  25.     override fun afterTextChanged(s: Editable?) {  
  26.     }  
  27.   
  28.     override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {  
  29.     }  
  30.   
  31.     override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {  
  32.         dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = !s.isNullOrBlank()  
  33.     }  
  34. })  
  35.   
  36. dialog.show()  
  37. dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false  




0 件のコメント:

コメントを投稿