How do I make a Spinner's “disabled” state look disabled?

后端 未结 13 1510
傲寒
傲寒 2020-12-09 03:00

When I disable my Spinner it looks almost exactly like it did prior to being disabled, i.e.

Before

相关标签:
13条回答
  • 2020-12-09 03:14

    For future reference, if you're using Kotlin, you can make use of extension functions, and provide a custom behaviour for disabled elements:

    fun Spinner.forceEnabled(isEnabled : Boolean){
        setEnabled(isEnabled)
        getChildAt(0)?.let{ childView ->
            childView.alpha = if (this.isEnabled) 1.0f else 0.33f
        }
        invalidate()
    }
    
    someSpinner.forceEnabled(true)
    

    This will allow to set custom properties to spinner children views, as the spinner is being disabled, without need for subclassing. Be cautious, as extension functions are resolved statically!

    0 讨论(0)
  • 2020-12-09 03:21

    One clever way of making spinners look disabled is to lower the transparency.

    Spinner spinner = (Spinner) findViewById(R.id.my_spinner);
    spinner.setEnabled(false);
    spinner.setAlpha(0.5f);
    
    0 讨论(0)
  • 2020-12-09 03:23

    I found this to be the best solution to the same question that was previously answered by @JSPDeveloper01: https://stackoverflow.com/a/20401876/8041634

    Since Android doesn't gray out the spinner when it has been set to disabled, he suggests creating a custom method that uses the .setAlpha command on the spinner, which grays out the text within it. Brilliant.

    0 讨论(0)
  • 2020-12-09 03:24
    ((Spinner) spnr).getSelectedView().setEnabled(false);
    ((Spinner) spnr).setEnabled(false);
    

    spnr is my Spinner object which refers to the XML view file, by findViewById(...).

    0 讨论(0)
  • 2020-12-09 03:24

    I've tried the following, and it's working as expected for me:

    _userMembership.setEnabled(false);
    _userMembership.setClickable(false);
    _userMembership.setAlpha((float)0.7);
    _userMembership.setBackgroundColor(Color.GRAY);
    
    0 讨论(0)
  • 2020-12-09 03:27

    Don't know if you still need this but there is a way. I've been struggling with this issue myself. I ended up doing something like this:

    ((Spinner) spinner).getSelectedView().setEnabled(false);
    spinner.setEnabled(false);
    

    What this actually does is disable the spinner and the selected item that is shown. Most likely the selected item is a TextView and it should show as a disabled TextView.

    I am using this and it works. But for some reason unknown to me it is not as "greyed-out" as other disabled views. It still looks disabled though. Try it out.

    0 讨论(0)
提交回复
热议问题