1. 自定义spinner下拉条目的样式custom_spinner.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_vertical" android:orientation="horizontal" android:padding="10dip" > <TextView android:id="@+id/label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" /> <ImageView android:id="@+id/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:src="@drawable/ic_sync_green_holo" android:visibility="visible" /> </LinearLayout>
2. 默认选中spinner样式 spinner.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="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:singleLine="true" android:textSize="22sp" />
3. 在activity的页面添加spinner控件
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="2" android:orientation="horizontal" > <Spinner android:id="@+id/video_call_spinner" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginRight="15dp" android:gravity="center_vertical" /> </LinearLayout>
4. 在java文件中添加绑定和监听
ArrayList<String> list = new ArrayList<String>(); list.add("Ask every time"); list.add("SIM A"); list.add("SIM B"); list.add("Country code"); voiceSpinner=(Spinner)mSimView.findViewById(R.id.voice_call_spinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.spinner, list){ @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { if(convertView==null){ convertView = getLayoutInflater().inflate(R.layout.custom_spinner, parent, false); } TextView label = (TextView) convertView.findViewById(R.id.label); ImageView icon = (ImageView) convertView.findViewById(R.id.icon); if(position==2) icon.setVisibility(View.VISIBLE); else icon.setVisibility(View.INVISIBLE); label.setText(getItem(position)); return convertView; } }; voiceSpinner.setAdapter(adapter); voiceSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Log.d("mark", "onItemSelected() is invoked!"); if(arg2==2) Log.i("wistron","2 selected++++++++++"); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } });