public class MainActivity extends AppCompatActivity
implements AdapterView.OnItemSelectedListener {
private TextView textview;
private Spinner spinner;
private List<String> list;
private ArrayAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview=(TextView) findViewById(R.id.textView);
spinner=(Spinner)findViewById(R.id.sPinner);
list=new ArrayList<String>();
//1.数据源
list.add("北京");
list.add("上海");
list.add("广州");
list.add("美国");
//2.适配器
adapter=new ArrayAdapter(this,android.R.layout.simple_spinner_item,list);
//3.adapter设置一个下拉列表样式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//4.装载适配器
spinner.setAdapter(adapter);
//5.设置监听器
spinner.setOnItemSelectedListener(this);
}
@Override//监听事件
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//String name=(String) adapter.getItem(i);
String name=(String)list.get(i);
textview.setText("你选择的城市是"+name);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}