//显示以及下拉样式
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
/>
<TextView
android:id="@+id/textView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="請選擇城市"
/>
</LinearLayout>
//MainActivity
public class MainActivity extends Activity {
private TextView tv;
private Spinner spn;
private List<Map<String,Object>>list; //数据源
private SimpleAdapter sim; //适配器
private String[]cityName={"北京","上海","廣州","深圳"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//綁定視圖
tv=(TextView) findViewById(R.id.textView1);
spn=(Spinner) findViewById(R.id.sp);
//list加載數據
list=new ArrayList<Map<String,Object>>();
getData();
//初始化數據適配器
sim=new SimpleAdapter(this, list, R.layout.item,new String[]{"name","pic"}, new int[]{R.id.textView,R.id.image});
//設置下拉樣式
sim.setDropDownViewResource(R.layout.item);
//設置數據適配器
spn.setAdapter(sim);
//設置監聽
spn.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
tv.setText(cityName[arg2]);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private void getData() {
// TODO Auto-generated method stub
for(int i=0;i<cityName.length;i++){
Map<String, Object>map=new HashMap<String, Object>();
map.put("name", cityName[i]);
map.put("pic", R.drawable.ic_launcher);
list.add(map);
}
}
}
/*有个未解决的问题,当监听事件用implements OnItemSelectedListener()并重新onItemSelected()方法实现时,tv.setText方法无法改变TextView中的内容*/