Я хочу перенаправить на другую ссылку при щелчке каждого слова текста текстового просмотра, поскольку я ищу это, я нашел решение, с помощью которого я получил щелчок по каждому слову текста текстового просмотра и мое первое перенаправление слова, чтобы связать его работу правильно, но другое слова не перенаправляют. Где я ошибаюсь?
Моя строка текстового просмотра:
Disclamer | Privacy Policy | Terms of Use \u2022 All Rights Reserved © company 2018.
Код:
disclamer = findViewById(R.id.disclamerText);
disclamer.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
mOffset = disclamer.getOffsetForPosition(motionEvent.getX(), motionEvent.getY());
// mTxtOffset.setText("" + mOffset);
if (findWordForRightHanded(disclamer.getText().toString(), mOffset).equalsIgnoreCase("Disclamer"))
{
Intent viewIntent = new Intent("android.intent.action.VIEW",
Uri.parse("https://www.company.com/disclaimer.php"));
startActivity(viewIntent);
}
if (findWordForRightHanded(disclamer.getText().toString(), mOffset).equalsIgnoreCase("Privacy"))
{
Intent viewIntent = new Intent("android.intent.action.VIEW",
Uri.parse("https://www.company.com/privacy.php"));
startActivity(viewIntent);
}
if (findWordForRightHanded(disclamer.getText().toString(), mOffset).equalsIgnoreCase("Terms"))
{
Intent viewIntent = new Intent("android.intent.action.VIEW",
Uri.parse("https://www.company.com/terms-and-cond.php"));
startActivity(viewIntent);
}
if (findWordForRightHanded(disclamer.getText().toString(), mOffset).equalsIgnoreCase("company"))
{
Intent viewIntent = new Intent("android.intent.action.VIEW",
Uri.parse("https://www.company.com"));
startActivity(viewIntent);
}
Toast.makeText(getApplicationContext(), findWordForRightHanded(disclamer.getText().toString(), mOffset), Toast.LENGTH_SHORT).show();
}
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);
}
он записан во многие действия, и для этого мне нужно изменить xml и активность каждого действия.
Я думаю, вы запутались. Прежде всего, значения x и y, полученные от объекта motionEvent, представляют X и Y экранные координаты касания, которые полностью отличаются от смещения, ожидаемого в качестве параметра для функции findWordForRightHanded. Смещение в findWordForRightHanded представляет индекс в текстовой строке.
Таким образом, вы не можете передать координаты из события движения в качестве смещения без функции сопоставления, которая сопоставит смещение каждого символа в строке с его координатами на экране.
Разве не было бы лучше создать отдельные
TextViewи определить на нихonClickListener?