Я бэкэнд-разработчик и новичок в Android. Я пытаюсь разработать программу для чтения книг, и есть бизнес-требование отображать в отдельном TextView слова, по которым пользователь нажимает во время чтения. Книги представлены в формате ePUB, поэтому для их отображения я использую WebView.
Мне удалось добиться этого в TextView с помощью getOffsetForPosition (), но я не нашел аналогичного решения для WebView, так как он использует HTML. Ниже приведен текст с getOffsetForPosition () и TextView.
public class MainActivity extends AppCompatActivity {
String desiredWord;
TextView showTranslatedText, mainTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showTranslatedText = (TextView)findViewById(R.id.showTranslatedText);
mainTextView = (TextView) findViewById(R.id.mainTextView);
mainTextView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
int mOffset = mainTextView.getOffsetForPosition(motionEvent.getX(), motionEvent.getY());
desiredWord = findWordForRightHanded(mainTextView.getText().toString(), mOffset);
showTranslatedText.setText(desiredWord);
Log.i("Reponse: ", "пошел вызов");
return false;
}
});
private String findWordForRightHanded(String str, int offset) { // when you touch ' ', this method returns left word.
if (str.length() == offset) {
offset--; // without this code, you will get exception when touching end of the text
}
if (str.charAt(offset) == ' ') {
offset--;
}
int startIndex = offset;
int endIndex = offset;
try {
while (str.charAt(startIndex) != ' ' && str.charAt(startIndex) != '\n') {
startIndex--;
}
} catch (StringIndexOutOfBoundsException e) {
startIndex = 0;
}
try {
while (str.charAt(endIndex) != ' ' && str.charAt(endIndex) != '\n') {
endIndex++;
}
} catch (StringIndexOutOfBoundsException e) {
endIndex = str.length();
}
// without this code, you will get 'here!' instead of 'here'
// if you use only english, just check whether this is alphabet,
// but 'I' use korean, so i use below algorithm to get clean word.
char last = str.charAt(endIndex - 1);
if (last == ',' || last == '.' ||
last == '!' || last == '?' ||
last == ':' || last == ';') {
endIndex--;
}
return str.substring(startIndex, endIndex);
}
Есть ли что-то похожее для WebView? Любой ответ будет полезен, спасибо.