Android 查找匹配的文字并显示红色

布局




    

        

        
    


代码

public class TextMatchActivity extends AppCompatActivity implements TextWatcher {

    private EditText editText;
    private String keyword;
    private String text;
    private TextView textView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_txt);

        editText = ((EditText) this.findViewById(R.id.et));
        textView = ((TextView) this.findViewById(R.id.tv));

        editText.addTextChangedListener(this);
        text = getResources().getString(R.string.txt);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

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

    }

    @Override
    public void afterTextChanged(Editable s) {
        keyword = s.toString().trim();
        SpannableString spannableString = matchSearchText(Color.RED, text, keyword);
        textView.setText(spannableString);
    }

    private SpannableString matchSearchText(int color, String txt, String keyword) {
        SpannableString spannableString = new SpannableString(txt);
        Pattern pattern = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(spannableString);
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            spannableString.setSpan(new ForegroundColorSpan(color),
                    start,
                    end,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }
}

你可能感兴趣的:(Android基础)