實作的效果:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyM2gjMzMzM2EzMyQDM1EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
MainActivity:
public class MainActivity extends Activity implements OnItemSelectedListener {
private TextView textView;
private Spinner spinner;
private List<String>list;
private ArrayAdapter<String>adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.textView);
spinner=(Spinner) findViewById(R.id.spinner);
//1.設定資料源(使用List)
list=new ArrayList<String>();
list.add("北京");
list.add("上海");
list.add("廣州");
list.add("深圳");
//2.建立數組擴充卡(ArrayAdatper),simple_spinner_item這個是未下拉的樣式
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
//3.adapter設定一個下拉清單(菜單)樣式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//4.spinner加載擴充卡
spinner.setAdapter(adapter);
//5.設定點選事件
spinner.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
//将選擇的城市顯示在textview中
textView.setText("你選擇了:"+list.get(position));
//也可以用adapter.getItem(position),效果是一樣的
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
main.xml:
<?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="vertical" >
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000"
android:textSize="20sp" />
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>