我有两个列表
列表1 = [您好,您好]
列表2 = [你好,我好吗
我想将列表1的每个元素与列表2进行比较,然后相应地更改元素的颜色,例如matched应该为绿色,unmatched应该为红色。请检查下图。输出应该是这样的。谁能告诉我我该怎么做?
答案 0 :(得分:1)
您可以通过在" "
String first = "Hello How are you";
String second = "Hello How me you";
String[] stringArrayFirst = first.split(" ");
String[] stringArraySecond = second.split(" ");
for(int i=0; i< stringArrayFirst.length; i++) {
if (stringArrayFirst[i].equals(stringArraySecond[i])) {
// use spannable to make this string to green
Spannable wordtoSpan = new SpannableString(stringArrayFirst[i]);
wordtoSpan.setSpan(new ForegroundColorSpan(Color.GREEN), 0, stringArrayFirst[i].length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// now set wordtoSpan on textview
}else {
// make it red
}
}
答案 1 :(得分:1)
@ Deluxe1是正确的,您应该在发布之前尝试一下以及一些代码。但是您的问题很有趣,所以这是我的解决方案。
public static CharSequence printDiff(Context context, String sentence1, String sentence2) {
String[] array1 = sentence1.split(" ");
String[] array2 = sentence2.split(" ");
SpannableStringBuilder sb = new SpannableStringBuilder(sentence1);
for (int i = 0; i < array1.length; i++) {
int colorRes;
if (i < array2.length) {
colorRes = array1[i].equals(array2[i]) ? R.color.green: R.color.red;
} else {
colorRes = R.color.green;
}
int startIndex = getStartIndexOf(array1, i);
int endIndex = startIndex + array1[i].length();
sb.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorRes)), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return sb;
}
public static int getStartIndexOf(String[] array, int index) {
int count = 0;
for (int i = 0; i < index; i++) {
count += array[i].length();
count++;
}
return count;
}