Pooja Pachchigar
Pooja Pachchigar

Reputation: 227

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

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"/>

Upvotes: 5

Views: 12933

Answers (4)

sanjay
sanjay

Reputation: 636

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.

Upvotes: 7

Pavan
Pavan

Reputation: 5136

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.

Upvotes: 12

Ferdous Ahamed
Ferdous Ahamed

Reputation: 21736

Add attribute android:clickable="false" and android:focusable="false" to your Spinner.

Try this:

<Spinner
    android:background="@drawable/bg_spinner"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:enabled="false"
    android:clickable="false"
    android:focusable="false"
    android:layout_marginRight="5dp"
    android:id="@+id/etgen"
    android:entries="@array/gender"
    android:paddingRight="10dp"
    android:paddingLeft="10dp"
    android:layout_weight="1" />

Upvotes: 3

Summved Jain
Summved Jain

Reputation: 890

You can use xml attribute android:enabled="false" this will disable the particular attribute and if you want to disable the form then you can go with defining it in root element.

Define onClick listener on the button and then enable the element that you want. Please share your code and I can modify accordingly.

Upvotes: 0

Related Questions