Как повторно изменить цвет слова в TextView - Android Studio? - PullRequest
2 голосов
/ 04 августа 2020

У меня есть этот код:

public class MainActivity extends AppCompatActivity {

@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextView tv = findViewById(R.id.tv);

    tv.setOnTouchListener(new View.OnTouchListener() {
        @SuppressLint("ResourceAsColor")
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                Integer mOffset = tv.getOffsetForPosition(motionEvent.getX(), motionEvent.getY());
                Toast.makeText(MainActivity.this, findWordForRightHanded(tv.getText().toString(), mOffset), Toast.LENGTH_SHORT).show();

            }
            return false;
        }
    });

}


private String findWordForRightHanded(String str, int offset) {
    if (str.length() == offset) {
        offset--;
    }

    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();
    }
    char last = str.charAt(endIndex - 1);
    if (last == ',' || last == '.' ||
            last == '!' || last == '?' ||
            last == ':' || last == ';') {
        endIndex--;
    }

    return str.substring(startIndex, endIndex);
}

}

От: Как отображать каждое нажатое слово из TextView

Теперь я хочу чтобы заменить сообщение Toast на команду, измените цвет этого слова на синий, но я не знаю, как это сделать. Вы можете помочь мне. Спасибо за помощь.

...