我这里有代码,它突出显示TextView中的所有单词,它们等于键入的字符串。通过按下/下一个按钮,它会突出显示当前找到的单词。
我试图做的是转到当前突出显示的那个词的位置。
我已将此代码添加到我的onClick
中myScroll.scrollBy(0, +20);
但它似乎并不是我正在寻找的东西
我也试过这样的事情
myScroll.scrollTo(0, selected); // getting the index of the highlighted word
// but it's not working
onClickListener以突出显示下一个单词
findViewById(R.id.next).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selected++;
String text = ((EditText) findViewById(R.id.editText)).getText().toString();
if(text.equals("") {}
else
selected = changeTextView(details, text, selected);
}
});
突出显示文字的方法
private int changeTextView(TextView tv, String target, int selected) {
if(selected < 0 ) {
selected = 0;
}
String bString = (String) tv.getText().toString();
int startSpan = 0, endSPan = 0;
Spannable spanRange = new SpannableString(bString);
int currentIndex = 0;
while(true) {
startSpan = bString.indexOf(target, endSpan);
endSpan = startSpan + target.lenght();
boolean isLast = bString.indexOf(target, endSpan) < 0;
if(startSpan < 0)
break;
ParcelableSpan span;
if(currentIndex == selected || isLast && selected > currentIndex) {
span = new BackgroundColorSpan(Color.LTGRAY);
if(isLast && selected > currentIndex) {
selected = currentIndex;
}
} else {
span = new BackgroundColorSpan(Color.YELLOW);
}
currentIndex++;
spanRange.setSpan(
span,
startSpan,
endSpan,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
tv.setText(spanRange);
if(currentIndex == 0) {
return -1;
} else {
return selected;
}
}