主要功能代码在aftertextchange方法中操作,之前用
SpannableStringBuilder方法会出现错误,不能被序列化,所以只好用html拼接的方法
private TextWatcher mTWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
int index;
if(editText.getText().toString().length() > 0){
clearBtn.setVisibility(View.VISIBLE);
wordEdt = editText.getText().toString().trim();
banks.clear();
for(int i = 0;i < branchList.size();i++){
BankBranch bankBranch = branchList.get(i);
bankBranch.setSearchName(null);
String bankName = bankBranch.getName();
// ForegroundColorSpan span = new ForegroundColorSpan(getResources().getColor(R.color.red));//要显示的颜色
// SpannableStringBuilder builder = new SpannableStringBuilder(bankBranch.getName());
index = bankName.indexOf(wordEdt);//从第几个匹配上
if(index != -1){
// builder.setSpan(span, index, index+wordEdt.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
bankBranch.setSearchName(bankName.substring(0,index)+getBankName(wordEdt)+bankName.substring(index+wordEdt.length(), bankName.length()));
banks.add(bankBranch);
}
}
if(adapter==null){
adapter = new BranchAdapter(banks);
listV.setAdapter(adapter);
}else{
adapter.notifyDataSetChanged();
}
}else{
banks.clear();
clearBtn.setVisibility(View.INVISIBLE);
for (int i = 0; i < branchList.size(); i++) {
branchList.get(i).setSearchName(null);
banks.add(branchList.get(i));
}
adapter.notifyDataSetChanged();
}
}
};
private class BranchAdapter extends BaseAdapter{
private ArrayList<BankBranch> list;
public BranchAdapter (ArrayList<BankBranch> list){
this.list=list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@SuppressLint("InflateParams")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(BankBranchActivity.this).inflate(
R.layout.simple_list_item, null);
holder.textV = (TextView) convertView.findViewById(R.id.item_text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
BankBranch branch = list.get(position);
if(branch.getSearchName() != null){
holder.textV.setText(Html.fromHtml(branch.getSearchName()));
}else{
holder.textV.setText(branch.getName());
}
return convertView;
}
private class ViewHolder{
TextView textV;
}
}
颜色设置的方法
/**
* name1
* @return
*/
public String getBankName(String name1){
String s1=""+name1+"";
return s1;
}