:
自定义Spinner其实包括两个部分:
第一部分是用来打开下拉列表的按钮,如图,这个绿色背景直接设置Spinner的背景就行,素材文件如下:
里面的文字需要注意下,Spinner控件没有直接修改文字的接口,这个文字实际上是在Adapter中设置,例如:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
R.layout.spinner_checked_text, gradeList);
gradeSpinner.setAdapter(adapter);
这个spinner_checked_text.xml的实现如下:
<?xml version="1.0" encoding="utf-8"?> <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"android:id="@android:id/text1"android:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center_vertical"android:padding="10dp"android:singleLine="true"android:textColor="@color/text_green"android:textSize="20sp" ></CheckedTextView>
必须是CheckedTextView,否则会出错。
第二部分就是那个弹出来的下拉窗口,这个是复写ArrayAdapter的getDropDownView()方法来实现的,代码如下:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),R.layout.spinner_checked_text, gradeList) {@Overridepublic View getDropDownView(int position, View convertView,ViewGroup parent) {View view = inflate(getContext(), R.layout.spinner_item_layout,null);TextView label = (TextView) view.findViewById(R.id.spinner_item_label);ImageView check = (ImageView) view.findViewById(R.id.spinner_item_checked_image);label.setText(gradeList.get(position));if (gradeSpinner.getSelectedItemPosition() == position) {view.setBackgroundColor(getResources().getColor(R.color.spinner_green));check.setImageResource(R.drawable.check_selected);} else {view.setBackgroundColor(getResources().getColor(R.color.spinner_light_green));check.setImageResource(R.drawable.check_unselect);}return view;}};adapter.setDropDownViewResource(R.layout.spinner_item_layout);
其中spinner_item_layout.xml的内容如下:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/spinner_light_green"android:padding="15dp" ><TextViewandroid:id="@+id/spinner_item_label"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_centerVertical="true"android:textColor="@color/text_green"android:textSize="17sp" /><ImageViewandroid:id="@+id/spinner_item_checked_image"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:src="@drawable/check_unselect" /></RelativeLayout>