Main代码
1 package spinnerdemo.example.administrator.spinnerdemo; 2 3 import android.app.Activity; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.widget.AdapterView; 8 import android.widget.ArrayAdapter; 9 import android.widget.Spinner; 10 import android.widget.TextView; 11 12 import java.util.ArrayList; 13 import java.util.List; 14 15 public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener{ 16 private Spinner spinner; 17 private TextView textView; 18 private List<String> list; 19 private ArrayAdapter<String> arrayAdapter; 20 21 @Override 22 protected void onCreate(Bundle savedInstanceState) { 23 /*使用Spinner的步骤: 24 1.添加一个下拉列表项的list,这里添加的项就是下拉列表的菜单项: 25 private List<String> list=new ArrayList<String>(); 26 list.add("上海"); 27 2.为下拉列表定义一个数组适配器(ArrayAdapter),这里使用到前面的LIst 28 adapter=new ArrayAdapter<String>(this,android.R.layout.simpe_spinner_item,list); 29 3.为适配器设置下拉列表下拉时候的菜单样式: 30 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 31 4.将适配器添加到下拉列表中 32 mySpinner.setAdapter(adapter) 33 5.为下拉列表设置各种事件的响应,这个事件响应菜单被选中; 34 mySpinner.setOnItemSelectedListener(new Spinner.OnIteSelectedListener())*/ 35 super.onCreate(savedInstanceState); 36 setContentView(R.layout.main); 37 spinner= (Spinner) findViewById(R.id.spinner); 38 textView= (TextView) findViewById(R.id.text); 39 textView.setText("您选择的城市为北京"); 40 /*添加下拉列表的list,添加的是下拉列表的菜单项*/ 41 list=new ArrayList<String>(); 42 list.add("北京"); 43 list.add("天津"); 44 list.add("上海"); 45 list.add("广州"); 46 /* 为下拉列表定义数组适配器*/ 47 arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list); 48 /*为数组适配器设置下拉列表下拉时候的菜单样式*/ 49 arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 50 /*将适配器添加到下拉列表中*/ 51 spinner.setAdapter(arrayAdapter); 52 spinner.setOnItemSelectedListener(this); 53 } 54 55 @Override 56 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 57 // String cityName=arrayAdapter.getItem(position); 58 String cityName=list.get(position); 59 textView.setText("您选择的城市"+cityName); 60 61 } 62 63 @Override 64 public void onNothingSelected(AdapterView<?> parent) { 65 66 } 67 }
main.xml代码
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/text" android:textColor="#ff0000" android:textSize="25sp" /> <Spinner android:layout_marginTop="10dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/spinner" ></Spinner> </LinearLayout>