how do I highlight the searched text in my search filter?

后端 未结 5 2359
无人及你
无人及你 2020-12-09 12:27

I am trying to do a search such that all the \"visible\" search letters should be highlighted. I tried using spannable but that didn\'t do the trick, maybe I wasnt doing it

5条回答
  •  萌比男神i
    2020-12-09 12:53

    This is only demo for highlight text, you can implement your self by calling highlight(searchText, originalText) in filter,

    public class MainActivity extends AppCompatActivity {
    EditText editText;
    TextView text;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText) findViewById(R.id.editText);
        text = (TextView) findViewById(R.id.textView1);
    
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
            }
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                    text.setText(highlight(editText.getText().toString(), text.getText().toString()));
            }
    
            @Override
            public void afterTextChanged(Editable s) {
    
            }
        });
    
    }
    
    public static CharSequence highlight(String search, String originalText) {
        String normalizedText = Normalizer.normalize(originalText, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();
        int start = normalizedText.indexOf(search);
        if (start <= 0) {
            return originalText;
        } else {
            Spannable highlighted = new SpannableString(originalText);
            while (start > 0) {
                int spanStart = Math.min(start, originalText.length());
                int spanEnd = Math.min(start + search.length(), originalText.length());
                highlighted.setSpan(new BackgroundColorSpan(Color.YELLOW), spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                start = normalizedText.indexOf(search, spanEnd);
            }
            return highlighted;
        }
     }
    }
    

提交回复
热议问题