一、前言
一丝感想
一直想着多写几篇博客,一个为了提升自己,也是给需要的人提供帮助。可惜,项目太近,琐事太多,实在闲不下来,唉。不管怎样,还是想抽点时间出来完成这篇博客!
进入正题
android 是自带有下拉框spinner控件的,但是android原生的Spinner控件是不支持用户输入的(据我所知),仅仅支持在数据列表确定的情况下进行选择。所以要实现一个手动输入的下拉框,我们需要自己手动实现。
在这里要感谢该博客给的灵感:https://blog.youkuaiyun.com/u013700040/article/details/52914070
大致思想是这样:通过一个EditText和一个ImageView的组合来实现控件,然后采用popupWindow进行界面弹出。
PopupWindow不了解的可以先去了解一下,这里不做深究,PopupWindow和AlertDialog相似,都是android用于与用户交互的对话框界面。
二、可输入Spinner实现
1、实现SpinnerPopupWindow类
- 作用:该类用于加载Spinner控件的下拉框界面,当点击自定义的Spinner时,会像android原生的Spinner那样弹出下拉供选择项。
- 代码:
/*
* @ Description:
* @ Time: 2019/5/18 18:40:24
* @ Author: lgy
*/
public class SpinnerPopupWindow<T> extends PopupWindow {
private List<T> datas;//listview数据
private NormalAdapter adapter;
private LayoutInflater inflater;
private ListView mListView;
private Context mContext; // 上下文参参数
public SpinnerPopupWindow(Context context, List<T> datas, AdapterView.OnItemClickListener clickListener){
super(context);
mContext=context;
inflater = LayoutInflater.from(context);
this.datas = datas;
init(clickListener);
}
private void init(AdapterView.OnItemClickListener clickListener){
View view = inflater.inflate(R.layout.spinner_window_layout, null);
setContentView(view);
setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
setFocusable(true);
ColorDrawable dw = new ColorDrawable(0x00);
setBackgroundDrawable(dw);
mListView = (ListView) view.findViewById(R.id.popup_listview);
mListView.setAdapter(adapter = new NormalAdapter(mContext,datas,R.layout.spinner_popup_item));
mListView.setOnItemClickListener(clickListener);
}
}
- 说明:代码比较简单,不做详细说明。将SpinnerPopupWindow定义为模板类,是为了方便扩展。在定义该类时传入一个类型即可。在构造函数中,传入一个 AdapterView.OnItemClickListener,该类型是适配器,也就是ListView的子项点击消息响应,以回调的形式传入。
- 界面:写完后,我们要手写一个界面来供该popupWindow加载(相当于Activity加载xml界面一样),命名为:spinner_window_layout,放在layout文件夹下。该界面代码应该只包含一个listView。代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/popup_listview"
android:scrollbars="none"
android:background="@drawable/round_edge_radius_tv_bl"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
- 资源背景:好吧,差点忘记了给出round_edge_radius_tv_bl资源文件了,这个资源文件是设置ListView的背景,可以自己设计,以下给出代码:
文件命名:round_edge_radius_tv_bl.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffff" /><!-- 背景填充颜色 -->
<stroke
android:width="1dp"
android:color="#30000000" /><!-- 描边,边框宽度、颜色 -->