I am trying to add a Hint in the spinner widget as there is no option of Hint as in EditText
, I want to show Gender as a Hint and when clicked it must show only Male and Female not the hint.
How it can be Done Only Using XML
XML code of spinner.
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner1"
android:entries="@array/gender"
android:layout_marginTop="10dp"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:layout_gravity="center_horizontal" />
String Array of the spinner
<string-array name="gender">
<item>Male</item>
<item>Female</item>
</string-array>
The trick is this line
use it in the onItemSelected. Here is my code with more context
if your Spinner not support android:prompt, should use android.support.v7.widget.AppCompatSpinner instead.
In the adapter you can set the first item as disabled. Below is the sample code
And set the first item to grey color.
And if the user selects the first item then do nothing.
Refer the below link for detail.
How to add a hint to Spinner in Android
There are two ways you can use spinner:
static way
and then set:
dynamic way
Note: It will work like a Hint but not actually it is.
May it help!
make your hint at final position in your string array like this City is the hint here
and then in your array adapter
so the adapter return just first two item and finally in onCreate() method or what ,,, make Spinner select the hint
Step 1:
Your array looks like. last item your hint
Ex : private String[] yourArray = new String[] {"Staff", "Student","Your Hint"};
Step 2:
Create HintAdpater.java (Just copy & paste)
This class not return last item.. So your Hint not displays.
HintAdapter.java
Step 3:
Set spinner adapter like this
Credit goes to @Yakiv Mospan from this answer - https://stackoverflow.com/a/22774285/3879847
I modify some changes only..