How to wrap lengthy text in a spinner? [duplicate]

Step 1. TextView with wrapped text

The first thing to do is to to force simple TextView to wrap text. Its easy:

<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:singleLine="false"
    android:text="very long text that will be wrapped to next line" />

Note the singleLine attribute here.

Step 2. Custom layout

Now we should somehow set singleLine attribute to false in TextView used by Spinner to show the item in the list.

In your code you probably have place where you create adapter to use it with Spinner:

this.mAdapter = ArrayAdapter.createFromResource(this, R.array.Planets,
                android.R.layout.simple_spinner_dropdown_item);

The idea is to copy the android.R.layout.simple_spinner_dropdown_item layout to your project. Then modify it by setting singleLine attribute to false in CheckedTextView:

For this, add file to res/layout folder named multiline_spinner_dropdown_item.xml with next code:

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    style="?android:attr/spinnerDropDownItemStyle"
    android:singleLine="false"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:ellipsize="marquee" />

Note that this file is identical to android.R.layout.simple_spinner_dropdown_item layout, except it has singleLine set to false now.

Step 3. Creating Adapter with custom layout

Modify your adapter creating code to:

this.mAdapter = ArrayAdapter.createFromResource(this, R.array.Planets,
                 R.layout.multiline_spinner_dropdown_item);

Here is screenshot from modified SpinnerActivity example from Android SDK:

enter image description here

Leave a Comment