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

I have two spinner and EditText controls within a table layout view on a separate row. The spinners are populated with data. My problem is the data (texts) that are populated into the spinners are too lengthy to fit the screen size. Therefore, the spinners are forced to stretch unnecessarily stretching other controls on another row.

It's a must for me to show the texts in the spinner. Hence using ellipses is not an option. If it's possible how can I wrap the lengthy text on the spinners?


Solution 1:

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