我需要完成一堆单词的出现,我在textview文本中可以点击
EG。 - 我的arraylist中有两个名字--Ajay和Dhananjay 并且让我说textview中的文字是........
@Ajay
,@Dhananjay
,我昨天与@Vijay进行了一场精彩的战斗
现在,我需要在我的textview中突出显示所有出现的@Ajay和@Dhananjay,并使它们也可以点击 但不是@Vijay(因为它不在我的arraylist中)
怎么做?
答案 0 :(得分:1)
我运行此代码并为我工作正常,请检查:
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());
}
}
答案 1 :(得分:1)
根据我的要求,Survivor's Answer中的一些修改对我有用。
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
。另一个是添加空格以及要突出显示的单词,以避免在较大的单词中突出显示子字符串。例如。 test in test123