Spinner

//显示以及下拉样式

<?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中的内容*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值