首先在xml文件添加Spinner控件:
<Spinner
android:id="@+id/mySpinner"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
在Activity中写:
package com.example.spinner;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
private Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner)this.findViewById(R.id.mySpinner);
//设置数据源
String[] mydata = {"北京", "上海","广东","广西"};
//声明一个ArrayAdapter,并将数据源与之关联起来
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,mydata);
//设置弹出下拉列表的风格
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//将arrayAdapter对象添加进Spinner去
spinner.setAdapter(adapter);
//添加监听器
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(MainActivity.this, "选择了:" + arg2, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}