Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable Spinner in Android and enable it on button click?

Tags:

android

I want disable my whole form including edittext and spinner and want to enable it when the user clicks on the edit form button.

Code:

 <Spinner
                        android:background="@drawable/bg_spinner"
                        android:layout_width="match_parent"
                        android:layout_height="40dp"
                        android:enabled="false"
                        android:layout_marginRight="5dp"
                        android:id="@+id/etgen"
                        android:entries="@array/gender"
                        android:paddingRight="10dp"
                        android:paddingLeft="10dp"
                        android:layout_weight="1"/>
like image 315
Pooja Pachchigar Avatar asked Nov 30 '22 22:11

Pooja Pachchigar


2 Answers

What I noticed here about Spinner that in XML we are not able to disable it using

 android:enabled='false'

It's not possible to enable/disable a Spinner in XML (yet). To do so you have to do it in code.

spinner.setEnabled(false);

If anyone knows any specific reason why so, they are welcome to edit.

like image 182
Pavan Avatar answered Dec 04 '22 12:12

Pavan


You have to disable it programmatically.

spinner.isEnabled = false

You can also change the color of it to give the disabled look like mentioned below. It will display the spinner in gray color.

 spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(p0: AdapterView<*>?) {
        }

        override fun onItemSelected(parent: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
            (parent?.getChildAt(0) as? TextView)?.setTextColor(Color.GRAY)

        }
    }

The above code is written in Kotlin. If you find any difficulty I can convert it to Java as well.

like image 21
sanjay Avatar answered Dec 04 '22 12:12

sanjay