Basic Spinner Example

suggest change

A Spinner is a dropdown input. Start with the layout. The id is what Java uses to find the view.

<Spinner
    android:id="@+id/cityArea"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</Spinner>

There are two main ways to populate a Spinner.

  1. From XML. Create res/values/arrays.xml and add this array:
<string-array name="defaultValue">
    <item>--Select City Area--</item>
    <item>--Select City Area--</item>
    <item>--Select City Area--</item>
</string-array>

Add this attribute to the Spinner XML:

android:entries="@array/defaultValue"
  1. You can also add values in Java.

In an activity:

cityArea = (Spinner) findViewById(R.id.cityArea);

In a fragment, call findViewById on the fragment's root view (for example view.findViewById(R.id.cityArea) in onCreateView). Fragment itself has no findViewById method.

Create an ArrayList of strings:

ArrayList<String> area = new ArrayList<>();
//add values in area arrayList
cityArea.setAdapter(new ArrayAdapter<String>(context
                            , android.R.layout.simple_list_item_1, area));

This will look like

The control's style follows the device's Android version and the app theme.

These are some of the default themes. If an app does not set a theme in its manifest, Android picks a default from targetSdkVersion so the app keeps the look it was built for:

targetSdkVersion Default theme
Version < 11 @android:style/Theme
Version between 11 and 13 @android:style/Theme.Holo
14 and higher @android:style/Theme.DeviceDefault

Set these attributes on the Spinner to customize it:

android:background="@drawable/spinner_background"

 android:layout_margin="16dp"

 android:padding="16dp"

Create a custom background in XML and use it.

Read the selected position from an item-selected listener:

cityArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            areaNo = position;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

Change the text color of the selected item in spinner

This can be done in two ways in XML

<item android:state_activated="true" android:color="@color/red"/>

This will change the selected item color in the popup.

From Java, do this inside onItemSelected. 0x00000000 is transparent, so use an opaque color such as red:

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    TextView selected = (TextView) parent.getChildAt(0);
    if (selected != null) {
        selected.setTextColor(0xFFFF0000);
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents