Demand analysis:

Make the keyword highlighted in the content of the query according to the keyword searched.

Let’s take a look at the effect:

Keywordutil.java is a tool class for color-changing text

package com.t20.searchdemo.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;

/** * text color change tools */
public class KeyWordUtil {

    /** ** keyword highlight color **@paramColor Changes the color value *@paramThe text text *@paramKeyword The keyword in the text *@returnResults SpannableString * /
    public static SpannableString matcherSearchTitle(int color, String text, String keyword) {
        SpannableString s = new SpannableString(text);
        keyword=escapeExprSpecialWord(keyword);
        text=escapeExprSpecialWord(text);
        if(text.contains(keyword)&&! TextUtils.isEmpty(keyword)){try {
                Pattern p = Pattern.compile(keyword);
                Matcher m = p.matcher(s);
                while (m.find()) {
                    int start = m.start();
                    int end = m.end();
                    s.setSpan(newForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); }}catch (Exception e){
            }
        }
        return s;
    }

    /** * Escape regular special characters ($()*+.[]? \ ^ {}, * * |)@param keyword
     * @return keyword
     */
    public static String escapeExprSpecialWord(String keyword) {
        if(! TextUtils.isEmpty(keyword)) { String[] fbsArr = {"\ \"."$"."(".")"."*"."+"."."."["."]"."?"."^"."{"."}"."|" };
            for (String key : fbsArr) {
                if (keyword.contains(key)) {
                    keyword = keyword.replace(key, "\ \"+ key); }}}returnkeyword; }}Copy the code

Rewrite the EditText input box cleareditText.java with the delete function

package com.t20.searchdemo.view;

import com.t20.searchdemo.R;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.Toast;

public class ClearEditText extends EditText implements  OnFocusChangeListener.TextWatcher {
	 /** * remove the reference to the button */
    private Drawable mClearDrawable; 
    /** * whether the control has focus */
    private boolean hasFoucs;
    
    private boolean isShow = false;
 
    public ClearEditText(Context context) { 
        this(context, null); 
    } 
 
    public ClearEditText(Context context, AttributeSet attrs) { 
        // The constructor is also important. Many attributes cannot be defined in XML without it
        this(context, attrs, android.R.attr.editTextStyle); 
    } 
    
    public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }
    
    
    private void init(a) { 
        GetCompoundDrawables () getCompoundDrawables() getCompoundDrawables() getCompoundDrawables(
        mClearDrawable = getCompoundDrawables()[2]; 
        if (mClearDrawable == null) {
            mClearDrawable = getResources().getDrawable(R.drawable.icon_del);
// throw new NullPointerException("You can add drawableRight attribute in XML");
        } 
        // Set the position and size of the icon,getIntrinsicWidth() gets the displayed size instead of the original image band size
        mClearDrawable.setBounds(0.0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight()); 
        // Hide ICONS by default
        setClearIconVisible(false); 
        // Set the focus change listener
        setOnFocusChangeListener(this); 
        // Set the listener for changes in the input box
        addTextChangedListener(this); 
    } 
 
 
    /** * Because we can't set click events directly to EditText, So we simulate the click event by remembering where we pressed * when the position we pressed is between the width of the EditText - the distance between the icon to the right of the control - the width of the icon and * the width of the EditText - the distance between the icon to the right of the control
    @Override 
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (getCompoundDrawables()[2] != null) {
                //getTotalPaddingRight() specifies the distance between the left edge of the icon and the right edge of the control
                //getWidth() -getTotalPaddingright () indicates the position from the left to the left edge of the icon
                //getWidth() -getPaddingright () indicates the position from the left to the right edge of the icon
                boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
                        && (event.getX() < ((getWidth() - getPaddingRight())));
                
                if (touchable) {
                    this.setText(""); }}// if(getCompoundDrawables()[0] ! = null){
// boolean touchLeft = event.getX()>0 && event.getX()
// if(touchLeft){
// if(isShow==false){
// isShow = true;
// // set to visible
// this.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
// }else{
// isShow = false;
// // Set the password mode
// this.setTransformationMethod(PasswordTransformationMethod.getInstance());
/ /}
/ /}
/ /}
        }

        return super.onTouchEvent(event);
    }
    /** * When the focus of ClearEditText changes, determine the length of the string set to clear the icon show and hide */
    @Override 
    public void onFocusChange(View v, boolean hasFocus) { 
        this.hasFoucs = hasFocus;
        if (hasFocus) { 
            setClearIconVisible(getText().length() > 0); 
        } else { 
            setClearIconVisible(false); }}/** * To set clear icon show and hide, call setCompoundDrawables to draw on EditText *@param visible
     */
    protected void setClearIconVisible(boolean visible) { 
        Drawable right = visible ? mClearDrawable : null; 
        setCompoundDrawables(getCompoundDrawables()[0], 
                getCompoundDrawables()[1], right, getCompoundDrawables()[3]); 
    }
    /** * Callback method when the contents of the input box change */
    @Override 
    public void onTextChanged(CharSequence s, int start, int count, 
            int after) { 
                if(hasFoucs){
                    setClearIconVisible(s.length() > 0); }}@Override 
    public void beforeTextChanged(CharSequence s, int start, int count, 
            int after) {}@Override 
    public void afterTextChanged(Editable s) {}/** * Set the slosh animation */
    public void setShakeAnimation(a){
        this.startAnimation(shakeAnimation(5));
    }
    
    
    /** * Shake animation *@paramCounts 1 Seconds how many shakes *@return* /
    public static Animation shakeAnimation(int counts){
        Animation translateAnimation = new TranslateAnimation(0.10.0.0);
        translateAnimation.setInterpolator(new CycleInterpolator(counts));
        translateAnimation.setDuration(1000);
        returntranslateAnimation; }}Copy the code

Activity_main.xml layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#F0F0F0"
        android:orientation="horizontal"
        android:padding="5dp" >

        <Button
            android:id="@+id/search_btn_2wm"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:alpha="0.7"
            android:background="@drawable/icon_qrcode" />

        <com.t20.searchdemo.view.ClearEditText
            android:id="@+id/search_editText_searchContent"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#fff"
            android:drawableLeft="@drawable/icon_search"
            android:drawablePadding="5dp"
            android:ems="10"
            android:hint="Enter an ID or name to search for"
            android:maxLines="1"
            android:padding="5dp"
            android:textColor="#ff9314"
            android:textSize="13sp" >
        </com.t20.searchdemo.view.ClearEditText>

        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="5dp" >

            <Button
                android:id="@+id/search_btn_back"
                android:layout_width="30dp"
                android:layout_height="35dp"
                android:alpha="0.7"
                android:background="@drawable/icon_right_back" />

            <TextView
                android:id="@+id/search_tv_search"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Search"
                android:textColor="#FF9316"
                android:textSize="13sp"
                android:visibility="gone" />
        </FrameLayout>
    </LinearLayout>

    <ListView
        android:id="@+id/search_listView_search_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>
Copy the code

Search_listview_item. XML layout, which is the ListView child layout

<? 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"
    android:padding="5dp"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/search_listView_item_iv_userHeadPic"
        android:layout_width="30dp"
        android:layout_height="30dp"       
        android:src="@drawable/head_default" />

    <TextView
        android:id="@+id/search_listView_item_tv_userNumber"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_marginLeft="20dp"
        android:textSize="16sp"
		android:gravity="center"
		android:textColor="# 666"
        android:text="123456" />

    <TextView
        android:id="@+id/search_listView_item_tv_userNick"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_marginLeft="20dp"
        android:textSize="16sp"
        android:gravity="center"
        android:textColor="# 666"
        android:text=Anonymous User />

</LinearLayout>
Copy the code

Mainactivity. ajva mainactivity. ajva mainactivity. ajva

package com.t20.searchdemo;

import java.util.ArrayList;
import java.util.List;

import com.t20.searchdemo.adapter.SearchListViewAdapter;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class MainActivity extends Activity implements OnClickListener {

	// Return button (close)
	private Button mButtonBack;
	/ / input box
	private EditText mEditTextSearchContent;
	// Search button
	private TextView mTextViewSearch;
	// The search content entered by the user
	private String searchContent;
	// Display the ListView for the search
	private ListView mListViewSearchResult;
	
	// Set of users
	private List<User> mUserList;
	//ListView adapter
	private SearchListViewAdapter mSearchListViewAdapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 1, hide the title bar, set before loading the layout (compatible with Android2.3.3 version)
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// hide the status bar
		//getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);				
		setContentView(R.layout.activity_main);
		initView();
		initEvent();
	}

	private void initEvent(a) {
		// TODO Auto-generated method stubClick on the input method software keyboard when the enter key, also can query mEditTextSearchContent directly. SetOnEditorActionListener (new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(! TextUtils.isEmpty(mEditTextSearchContent.getText())) {// Keep the cursor at the end of the input box
					mEditTextSearchContent.setSelection(mEditTextSearchContent.getText().length());
				}
				// Both actionId == XX_SEND and XX_DONE are triggered
				Or event.getKeyCode == ENTER and event.getAction == ACTION_DOWN
				// Note that this is the event that must be judged! = null. Because null is returned in some input methods.
				if(actionId == EditorInfo.IME_ACTION_SEND || actionId == EditorInfo.IME_ACTION_DONE || (event ! =null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
					// Press Enter on the input method soft keyboard to query
					search();
				}
				return true;// True means you consume the event}}); }private void initView(a) {
		// TODO Auto-generated method stub
		mButtonBack=(Button) findViewById(R.id.search_btn_back);
		mEditTextSearchContent=(EditText) findViewById(R.id.search_editText_searchContent);
		mTextViewSearch=(TextView) findViewById(R.id.search_tv_search);
		mListViewSearchResult=(ListView) findViewById(R.id.search_listView_search_result);
		// Set the listener
		mButtonBack.setOnClickListener(this);
		mTextViewSearch.setOnClickListener(this);
		mEditTextSearchContent.setOnClickListener(this);
		mEditTextSearchContent.addTextChangedListener(textWatcher);
	}
	
	private TextWatcher textWatcher=new TextWatcher() {
		
		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void afterTextChanged(Editable editable) {
			// TODO Auto-generated method stub
			// Get the contents of the input box
			String content=mEditTextSearchContent.getText().toString();
			// When the input box is empty, the return button is displayed and the search button is hidden
			if(content.isEmpty()){
				mTextViewSearch.setVisibility(View.GONE);
				mButtonBack.setVisibility(View.VISIBLE);
				mListViewSearchResult.setVisibility(View.GONE);
			}else{ mTextViewSearch.setVisibility(View.VISIBLE); mButtonBack.setVisibility(View.GONE); mListViewSearchResult.setVisibility(View.VISIBLE); }}};@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		// Click the search box
		case R.id.search_editText_searchContent:
			mEditTextSearchContent.setFocusable(true);
			mEditTextSearchContent.setFocusableInTouchMode(true);
			mEditTextSearchContent.requestFocus();		
			InputMethodManager imm=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.showSoftInput(mEditTextSearchContent, 0);
			break;
		// Close the button
		case R.id.search_btn_back:
			finish();
			break;
		// Click search
		case R.id.search_tv_search:
			search();
			break; }}/** * search for data */
	private void search(a) {
		// TODO Auto-generated method stub
		// Get what the user is searching for
		searchContent=mEditTextSearchContent.getText().toString();
		// Initialize some data (in real development, read from database)
		mUserList=new ArrayList<MainActivity.User>();
		User u1=new User(1."4346546"."Zhang");
		User u2=new User(1."3346565"."Bill");
		User u3=new User(1."6865879"."Fifty");
		User u4=new User(1."5745786"."Daisy");
		mUserList.add(u1);
		mUserList.add(u2);
		mUserList.add(u3);
		mUserList.add(u4);
		// Set the adapter
		mSearchListViewAdapter=new SearchListViewAdapter(MainActivity.this, mUserList, searchContent);
		mListViewSearchResult.setAdapter(mSearchListViewAdapter);
	}
	/** * Define a user class */
	public class User {
		Integer id;   //Id
		String number;/ / account
		String nick;  / / nickname
		public Integer getId(a) {
			return id;
		}
		public void setId(Integer id) {
			this.id = id;
		}
		public String getNumber(a) {
			return number;
		}
		public void setNumber(String number) {
			this.number = number;
		}
		public String getNick(a) {
			return nick;
		}
		public void setNick(String nick) {
			this.nick = nick;
		}
		
		public User(a) {
			super(a); }public User(Integer id, String number, String nick) {
			super(a);this.id = id;
			this.number = number;
			this.nick = nick; }}}Copy the code

Five, the custom SearchListViewAdapter. Java adapter

package com.t20.searchdemo.adapter;

import java.util.List;

import com.t20.searchdemo.MainActivity.User;
import com.t20.searchdemo.R;
import com.t20.searchdemo.util.KeyWordUtil;

import android.content.Context;
import android.graphics.Color;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class SearchListViewAdapter extends BaseAdapter {

	private Context context;
	private List<User> mUserList;	
	private String searchContent;// What the user is searching for

	public SearchListViewAdapter(Context context, List
       
         mUserList, String searchContent)
        {
		super(a);this.context = context;
		this.mUserList = mUserList;
		this.searchContent = searchContent;
	}

	public void setSearchContent(String searchContent) {
		this.searchContent = searchContent;
	}


	@Override
	public int getCount(a) {
		// TODO Auto-generated method stub
		return mUserList.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		// Get the object
		User user=mUserList.get(position);
		// Load the layout
		View view;
		ViewHolder viewHolder;
		if(convertView==null){
			view=LayoutInflater.from(context).inflate(R.layout.search_listview_item,null);
			viewHolder=new ViewHolder();
			// Get the control
			viewHolder.textViewNumber=(TextView) view.findViewById(R.id.search_listView_item_tv_userNumber);
			viewHolder.textViewNick=(TextView) view.findViewById(R.id.search_listView_item_tv_userNick);
			// Store the ViewHolder in the View
			view.setTag(viewHolder);
		}else{
			view=convertView;
			// Retrieve the ViewHolder
			viewHolder=(ViewHolder) view.getTag();			
		}
		// Sets the value of the control
		// The search is highlighted
		if(user.getNumber()! =null&&user.getNumber().length()>0){
			SpannableString number=KeyWordUtil.matcherSearchTitle(Color.parseColor("#ff9314"), user.getNumber()+"", searchContent);	
			viewHolder.textViewNumber.setText(number);
		}
		if(user.getNick()! =null&&user.getNick().length()>0){
			SpannableString nick=KeyWordUtil.matcherSearchTitle(Color.parseColor("#ff9314"), user.getNick(), searchContent);
			viewHolder.textViewNick.setText(nick);
		}		
		
		return view;
	}
	class  ViewHolder{ TextView textViewNumber; TextView textViewNick; }}Copy the code