1.使用AutoCompleteTextView完成搜索提示自動(dòng)補(bǔ)全功能,多數(shù)教程是使用默認(rèn)ArrayAdapter,但是定制性不高漂辐,下面說說自定義的adapter,以下是代碼:
//實(shí)現(xiàn)過濾 重寫過濾條件
private List<CompanyBean.DataBean> datas;
private List<CompanyBean.DataBean> Unfilterdatas;//未進(jìn)行過濾的數(shù)據(jù)
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) {
//文本框內(nèi)容開始篩選
FilterResults filterResults = new FilterResults();//過濾結(jié)果對(duì)象 values值 count大小
if (Unfilterdatas.size() == 0) {
return null;
}
if (constraint == null || constraint.length() == 0) {
//未輸入東西默認(rèn)所有展示 可更具需求設(shè)定
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)) {
//此處是業(yè)務(wù)需求所有未過濾數(shù)據(jù)中篩選出包含輸入的內(nèi)容 可根據(jù)場(chǎng)景修改
newDatas.add(dataBean);
}
}
if (newDatas.size() == 0) {
//篩選結(jié)果沒有展示所有數(shù)據(jù)
filterResults.values = Unfilterdatas;
filterResults.count = Unfilterdatas.size();
} else {
//設(shè)置篩選結(jié)果數(shù)據(jù)
filterResults.values = newDatas;
filterResults.count = newDatas.size();
}
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//給適配器數(shù)據(jù)刷新
if(results!=null){
//修改適配器數(shù)據(jù)
datas = (ArrayList<CompanyBean.DataBean>) results.values;
}
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
2.如果展示出來的列表跑到控件上方則是因?yàn)檐涙I盤的影響,所以需要設(shè)置
android:windowSoftInputMode="adjustPan|adjustResize
調(diào)整一下就完畢