扩展自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;
<
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
);
大功告成!!!
类似效果图