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

梦想的初衷 提交于 2019-11-27 00:58:28

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:

Define a custom layout and use it with the spinner and adapter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!