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>
In the adapter you can set the first item as disabled. Below is the sample code
@Override
public boolean isEnabled(int position) {
if (position == 0) {
// Disable the first item from Spinner
// First item will be use for hint
return false;
} else {
return true;
}
}
And set the first item to grey color.
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if (position == 0) {
// Set the hint text color gray
tv.setTextColor(Color.GRAY);
} else {
tv.setTextColor(Color.BLACK);
}
return view;
}
And if the user selects the first item then do nothing.
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedItemText = (String) parent.getItemAtPosition(position);
// If user change the default selection
// First item is disable and it is used for hint
if (position > 0) {
// Notify the selected item text
Toast.makeText(getApplicationContext(), "Selected : " + selectedItemText, Toast.LENGTH_SHORT).show();
}
}
Refer the below link for detail.