1.使用AutoCompleteTextView完成搜索提示自动补全功能,多数教程是使用默认ArrayAdapter,但是定制性不高,下面说说自定义的adapter,以下是代码:
//实现过滤 重写过滤条件
private List<CompanyBean.DataBean> datas;
private List<CompanyBean.DataBean> Unfilterdatas;//未进行过滤的数据
public ChannelCompanyAdapter(List<CompanyBean.DataBean> datas) {
this.datas = datas;
Unfilterdatas = datas;
}
@Override
public int getCount() {
return datas.size();
}
@Override
public CompanyBean.DataBean getItem(int position) {
return datas.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Vholder vholder = null;
if (convertView == null) {
vholder = new Vholder();
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.textview_auto, parent, false);
vholder.tv = convertView.findViewById(R.id.tv);
convertView.setTag(vholder);
} else {
vholder = (Vholder) convertView.getTag();
}
vholder.tv.setText(getItem(position).getUsername());
return convertView;
}
@Override
public Filter getFilter() {
return new MyFilter();
}
class Vholder {
private TextView tv;
}
class MyFilter extends Filter {
//核心过滤
@Override
protected FilterResults performFiltering(CharSequence constraint) {
//文本框内容开始筛选
FilterResults filterResults = new FilterResults();//过滤结果对象 values值 count大小
if (Unfilterdatas.size() == 0) {
return null;
}
if (constraint == null || constraint.length() == 0) {
//未输入东西默认所有展示 可更具需求设定
filterResults.values = Unfilterdatas;
filterResults.count = Unfilterdatas.size();
} else {
String s = constraint.toString().toLowerCase();
ArrayList<CompanyBean.DataBean> newDatas = new ArrayList<>();
for (CompanyBean.DataBean dataBean : Unfilterdatas) {
if (dataBean.getUsername().contains(s)) {
//此处是业务需求所有未过滤数据中筛选出包含输入的内容 可根据场景修改
newDatas.add(dataBean);
}
}
if (newDatas.size() == 0) {
//筛选结果没有展示所有数据
filterResults.values = Unfilterdatas;
filterResults.count = Unfilterdatas.size();
} else {
//设置筛选结果数据
filterResults.values = newDatas;
filterResults.count = newDatas.size();
}
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//给适配器数据刷新
if(results!=null){
//修改适配器数据
datas = (ArrayList<CompanyBean.DataBean>) results.values;
}
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
2.如果展示出来的列表跑到控件上方则是因为软键盘的影响,所以需要设置
android:windowSoftInputMode="adjustPan|adjustResize
调整一下就完毕