1.设置下拉框的值
1.1通过xml entries属性配置
需要将数据写在xml中,然后设置下拉框的entries属性,则数据自动加载到下拉框中。具体如下:
layout布局引用
<Spinner android:layout_weight="1.5" android:id="@+id/sp_bound_rate" android:layout_width="0dp" android:layout_height="40dp" android:background="#E5E5E5" android:dropDownVerticalOffset="45dp" android:spinnerMode="dropdown" android:entries="@array/baudrates_value" tools:ignore="MissingConstraints" />
在value文件夹中新建cityInfo.xml,xml中写入
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="boundrates_value"> <item>北京</item> <item>江苏</item> <item>浙江</item> <item>上海</item> </string-array> </resources>
1.2通过 Java代码配置
1.获得数据列表;2.填充数据适配器;3.设置下拉框的适配器;
private Spinner spCity = null; private ArrayAdapter<CharSequence> adapterCity = null; private static String[] cityInfo={"北京","江苏","浙江","上海"}; //初始化函数中代码如下 this.spCity = (Spinner) super.findViewById(R.id.spinnerCity); //将数据cityInfo填充到适配器adapterCity中 this.adapterCity = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_dropdown_item, cityInfo); //设置下拉框的数据适配器adapterCity this.spCity.setAdapter(adapterCity);
2选择时触发的事件 setOnItemSelectedListener
sp_rate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
注意:adapterView 对应的是spinner view对应的是spinner内部每一行的布局的view @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { editor.putString("BAUDRATE",adapterView.getSelectedItem().toString()); editor.commit(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } });
3.获得下拉框所选的值
adapterView.getSelectedItem().toString()
adapterView.getItemAtPosition(position).toString();
sp_rate.getSelectedItem().toString()
Android 中 Spinner下拉框使用 - 掘金 (juejin.cn)
baudrates_value 标签:xml,adapterCity,适配器,下拉框,spinner,使用,Android,adapterView From: https://www.cnblogs.com/wanglongjiang/p/17390388.html