13
6

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 5 years have passed since last update.

【Kotlin】Activityからボタンのクリックを無効にする

Last updated at Posted at 2019-04-10

Activityからボタンのクリックを無効にするには**isClickable**を使います。

良い例
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button.setOnClickListener {
            Toast.makeText(applicationContext, "ボタンをクリックしました", Toast.LENGTH_SHORT).show()
        }

        // クリックを無効にする
        button.isClickable = false
    }
}

注意点としては、setOnclickLisnter後に記述すること
setOnclickLisnterがクリックのフラグをtrueに変更してしまうためです。
android - Button.setClickable(false) is not working - Stack Overflow

悪い例
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 無効にならない
        button.isClickable = false

        button.setOnClickListener {
            Toast.makeText(applicationContext, "ボタンを押しました", Toast.LENGTH_SHORT).show()
        }
    }
}

ちなみに、iOSだとisEnable=trueを設定したボタンは文字色がグレーになるので非活性だとわかりやすいのですが、
Androidではクリックが有効であれ無効であれ見た目は変わらないので、別途ボタンの色や透明度を変更してあげる必要がありそうです。

追記

**isEnabled**を使えば、文字色がグレーになることがわかりました!
isClickableと違ってリスナーの影響は受けないようなので、前後どちらに書いても大丈夫です。)

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // クリックを無効にする + 文字のグレーアウト
        button.isEnabled = false

        button.setOnClickListener {
            Toast.makeText(applicationContext, "ボタンを押しました", Toast.LENGTH_SHORT).show()
        }
    }
}

単にクリックを無効化したい場合はisClickableを使い、その上でユーザーに使えないよと示したい場合にはisEnabledを使うと良さそうだなと思いました。
ご指摘頂いた @entan05 さん、ありがとうございました:sparkles:

13
6
2

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
13
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?