<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SpinnerTest"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000"
android:textSize="20sp"
></TextView>
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
></Spinner>
</LinearLayout>
public class SpinnerTest extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
//声明变量
private TextView textView;
private Spinner spinner;
private List<String> data = new ArrayList<>();
private ArrayAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_test);
textView = findViewById(R.id.textView);
spinner = findViewById(R.id.spinner);
textView.setText("您选择的城市是北京");
//添加数据源,就是下拉菜单选项
data.add("北京");
data.add("上海");
data.add("广州");
data.add("重庆");
//为下拉列表定义一个数组适配器
adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,data);
//为适配器设置下拉列表下拉时的菜单样式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//将适配器配置到下拉列表上
spinner.setAdapter(adapter);
//给下拉菜单设置监听事件
spinner.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String cityName = data.get(i);
textView.setText("您选择的城市是"+cityName);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}