我想在单击textview文本的每个单词时重定向到不同的链接,在搜索时,我找到了解决方案,通过该解决方案,我单击了textview文本的每个单词,并第一个单词重定向来链接其工作正确,但其他字词未重定向。我要去哪里错了?
我的textview字符串是:
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);
}
答案 0 :(得分:0)
我觉得你很困惑。首先,从motionEvent对象获得的x和y值表示触摸的X和Y屏幕坐标,这与作为findWordForRightHanded函数的参数的期望偏移量完全不同。 findWordForRightHanded中的偏移量表示字符串文本中的索引。
因此,如果没有映射功能,就无法将运动事件中的坐标作为偏移量传递,该函数会将字符串中的每个字符偏移量映射到屏幕中的坐标