添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

How to wrap lengthy text in a spinner

参考自: http://stackoverflow.com/questions/6107500/how-to-wrap-lengthy-text-in-a-spinner
扩展自Adapter 的适配器是在Spinner与数据之间的一座桥梁。一个Spinner Adapter允许定义两个不同的视图:一是在Spinner上显示数据,另一个是当Spinner按下时在下拉列表里显示数据。重载getDropDownView(int position, View convertView,ViewGroup parent)及getView(int position, View convertView, ViewGroup parent)方法。
第一步:将spinner使用的TextView 的singleLine属性设为false,即: tv.setSingleLine( false );
private class SpinnerAdapter extends ArrayAdapter<String> {
Context context ;
String[] items = new String[] {};
public SpinnerAdapter( final Context context,
final int textViewResourceId, final String[] objects) {
super (context, textViewResourceId, objects);
this . items = objects;
this . context = context;
@Override
public View getDropDownView( int position, View convertView,
ViewGroup parent) {
if (convertView == null ) {
LayoutInflater inflater = LayoutInflater. from ( context );
convertView = inflater.inflate(
R.layout. multiline_spinner_dropdown_item , parent, false );
TextView tv = (TextView) convertView.findViewById(android.R.id. text1 );
tv.setSingleLine( false );
tv.setText( items [position]);
tv.setTextColor(Color. BLACK );
//            tv.setTextSize(20);
return convertView;
@Override
public View getView( int position, View convertView, ViewGroup parent) {
if (convertView == null ) {
LayoutInflater inflater = LayoutInflater. from ( context );
convertView = inflater.inflate(
android.R.layout. simple_spinner_item , parent, false );
// android.R.id.text1 is default text view in resource of the android.
// android.R.layout.simple_spinner_item is default layout in resources of android.
TextView tv = (TextView) convertView.findViewById(android.R.id. text1 );
tv.setSingleLine( false );
tv.setText( items [position]);
tv.setTextColor(Color. BLACK );
//            tv.setTextSize(20);
return convertView;
这个方法的关键是拷贝 android.R.layout.simple_spinner_dropdown_item 下的layout到自己的项目中,并将 CheckedTextView 下的singleLine属性设置为false;为此,先在res/layout目录下创建一个名为multiline_spinner_dropdown_item.xml的文件,代码如下:
< 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" />
第三步:声明Spinner并将其与适配器( SpinnerAdapter )关联
spinner_patrol =(Spinner)findViewById(R.id. spinner_patrol );
SpinnerAdapter adapter = new SpinnerAdapter( this ,
R.layout. multiline_spinner_dropdown_item , xccqcsArray );
大功告成!!! 类似效果图
转载请标明出处: http://www.cnblogs.com/sciseeker/