Spinner下拉列表的使用
直接来一个效果
Spinner下拉列表的使用
1 Spinner本身的布局文件
<Spinner
android:id="@+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:spinnerMode="dropdown" />
2 Spinner两个布局文件
正常下拉展示文件item_dropdown.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="45dp"
android:textColor="@android:color/black"
android:textSize="14sp"
android:gravity="center"/>
选中下拉文件item_select.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="45dp"
android:background="@android:color/background_light"
android:gravity="center"
android:textColor="@android:color/holo_red_light"
android:textSize="20sp" />
3 配置代码
// 使用到的变量
private Spinner spList;
String[] starArray= {"水星","金星","地球","火星","木星","土星"};
//设置代码
spList=findViewById(R.id.spinner2);
//声明一个下拉列表的数组适配器
ArrayAdapter<String> starAdapter = new ArrayAdapter<String>(getActivity(),R.layout.item_select,starArray);
//设置数组适配器的布局样式
starAdapter.setDropDownViewResource(R.layout.item_dropdown);
//设置下拉框的标题,不设置就没有难看的标题了
spList.setPrompt("请选择图片");
//设置下拉框的数组适配器
spList.setAdapter(starAdapter);
//设置下拉框默认的显示第一项
spList.setSelection(0);
//给下拉框设置选择监听器,一旦用户选中某一项,就触发监听器的onItemSelected方法
spList.setOnItemSelectedListener(new MySelectedListener());
4 选中消息响应类
//spin消息监听类
class MySelectedListener implements AdapterView.OnItemSelectedListener{
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
imgDisplay.setImageResource(R.mipmap.a13);
if(i>=0 && i<=WxpPicArray2.length) {
String picName = starArray[i];
//自己使用获取到的选择项
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
还没有评论,来说两句吧...