如何在Android中输入单词时突出显示单词

时间:2016-07-29 13:34:25

标签: android

我希望 EditText 区域按照 textView 工作方式工作,当我输入时让它突出显示某些特定字词,如 textView 有效。这段代码就是我所做的,但是当我输入它时它不起作用

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.span_test);
    String str = " This is as a result of instances in this matter and "
            + "as it is has look as this. So and this3 goes on manthis "
            +"and also thisman like this gen ,";
    String regex = "\\bthis\\b";
    textView = (TextView)findViewById(R.id.span_test);
    SpannableString spstr = new SpannableString(str);
    Pattern patern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    Matcher matcher = patern.matcher(spstr.toString());
    while(matcher.find()){
        spstr.setSpan(new ClickableSpan(){
            @Override
            public void onClick(View wiget){
                Toast.makeText(SpanTestActivity.this,
                        "Clicked" + "styledString. ", Toast.LENGTH_SHORT).show();
            };}, matcher.start(), matcher.end(), 0);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
    }
    textView.setText(spstr);

    editText = (EditText)findViewById(R.id.span_test1);
    spstr = new SpannableString(editText.toString());
    patern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    matcher = patern.matcher(spstr.toString());
    while(matcher.find()){
        spstr.setSpan(new ClickableSpan(){
            @Override
            public void onClick(View wiget){
                Toast.makeText(SpanTestActivity.this,
                        "Clicked" + "styledString. ", Toast.LENGTH_SHORT).show();
            };}, matcher.start(), matcher.end(), 0);
        editText.setMovementMethod(LinkMovementMethod.getInstance());
    }
    editText.setText(spstr);
}

1 个答案:

答案 0 :(得分:0)

您需要使用TextWatcher ()

您可以找到文档here

因为在用户输入时,您想要做的是找到一个特定的单词。 TextWatcher始终在TexView中监听更改。检查documentation是否有TextView

所以你需要做的就是下一个:

youtTextView.addTextChangedListener(TextWatcher watcher)