1. 程式人生 > >Android關鍵字模糊查詢,並帶有高亮效果

Android關鍵字模糊查詢,並帶有高亮效果

主要功能程式碼在aftertextchange方法中操作,之前用

SpannableStringBuilder方法會出現錯誤,不能被序列化,所以只好用html拼接的方法

privateTextWatchermTWatcher=newTextWatcher(){

@Override

public void onTextChanged(CharSequence s, int start, int before, int count) {

}

@Override

publicvoidbeforeTextChanged(CharSequence s,int start,int count,

int

after) {

}

@Override

publicvoidafterTextChanged(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=newBranchAdapter(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();

}

}

};

privateclassBranchAdapterextendsBaseAdapter{

private ArrayList<BankBranch> list;

public BranchAdapter (ArrayList<BankBranch> list){

this.list=list;

}

@Override

publicintgetCount(){

returnlist.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;

}

privateclassViewHolder{

TextViewtextV;

}

}


顏色設定的方法

/**

*  name1   

* @return

*/

publicStringgetBankName(String name1){

String s1="<font color=\"#990000\">"+name1+"</font>";

return s1;

}