How to grey out a button?

后端 未结 9 731
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-22 22:23

I have a button defined as shown below. When I want to disable it I use my_btn.setEnabled(false), but I would also like to grey it out. How can I do that?

9条回答
  •  一生所求
    2020-12-22 22:41

    You could Also make it appear as disabled by setting the alpha (making it semi-transparent). This is especially useful if your button background is an image, and you don't want to create states for it.

    button.setAlpha(.5f);
    button.setClickable(false);
    

    update: I wrote the above solution pre Kotlin and when I was a rookie. It's more of a "quick'n'dirty" solution, but I don't recommend it in a professional environment.

    Today, if I wanted a generic solution that works on any button/view without having to create a state list, I would create a Kotlin extension.

    fun View.disable() {
        getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
        setClickable(false)
    }
    

    In Java you can do something is similar with a static util function and you would just have to pass in the view as variable. It's not as clean but it works.

提交回复
热议问题