如何使文本视图中特定单词的出现可点击

How to make specific words' occurrences in a textview clickable

我需要使文本视图文本中出现的所有单词都可点击

例如。 - 我的数组列表中有 2 个名字 - Ajay 和 Dhananjay 假设我的文本视图中的文本是......

@Ajay, @Dhananjay, I just had a great fight with @Vijay yesterday

现在,我只需要突出显示我的文本视图中所有出现的@Ajay 和@Dhananjay,并让它们也可以点击 但不是@Vijay(因为它不在我的数组列表中)

如何操作?

我运行这段代码对我来说工作得很好,检查它:

public class MainActivity extends AppCompatActivity {
TextView text;
String string = "@Ajay, @Dhananjay, I just had a great fight with @Vijay yesterday";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.textView1);
    SpannableString ss = new SpannableString(string);
    String[] words = string.split(" ");
    for (final String word : words) {
        if (word.startsWith("@") && word.endsWith(",")) {
            ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void onClick(View textView) {
                    //use word here to make a decision
                }
            };
            ss.setSpan(clickableSpan, string.indexOf(word), string.indexOf(word) + word.length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    text.setText(ss);
    text.setMovementMethod(LinkMovementMethod.getInstance());
}
}

根据我的要求, 中的一些修改对我有用。

  text = (TextView) findViewById(R.id.textView1);

  string += " ";

    SpannableString ss = new SpannableString(string);
    String[] words = string.split(" ");
    for (final String word : words) {
       if (word.startsWith("@") && mentionsNamesList.contains(word.substring(1))) {
             int lastIndex = 0;

            while(lastIndex != -1){

                lastIndex = string.indexOf(word+" ",lastIndex);

                if(lastIndex != -1){
            ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void onClick(View textView) {
                    //use word here to make a decision
                }
            };
          ss.setSpan(clickableSpan, lastIndex, lastIndex + word.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

          lastIndex += word.length();
         }
        }
    }
    text.setText(ss);
    text.setMovementMethod(LinkMovementMethod.getInstance());

所做的修改包括 use of while loop in order to highlight and make clickable every occurrence of the word in the whole textview,instead of only the first one。另一个是添加 space 以及要突出显示的单词,以避免突出显示较大单词中出现的子字符串。例如。 test in test123