如何从 android 文本视图(多行)中删除一个词而不影响其他词的 alignment/position

How to delete one word from a android textview (multiple lines) without affecting the alignment/position of other words

我有一个 android 文本视图,我正在为它设置 10 个单词的句子。

现在,我需要删除一个单词(比如第 4 个单词)而不影响剩余单词的 positions/alignment。

请参考下图。另请注意,如果我用空格替换该特定单词,剩余单词的对齐方式仍会略有变化,因为每个字符的宽度不同。

如何使用textview实现它?任何帮助深表感谢。谢谢

您可以使用 SpannableString 将背景颜色(在您的图片中看起来像白色)应用于应该消失的字母。

如果你想将效果应用到第四个单词(“sample”),那么你可以写

val startOfWord = 11
val endOfWord = 16
val spannable = SpannableString(“This is my sample text goes ...”)
spannable.setSpan(ForegroundColorSpan(Color.WHITE), 
     startOfWord, endOfWord + 1, 
     Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

exampleTextView.text = spannable

另请参阅 Florina Muntenescu 的 Spantastic text styling with Spans

这是一个算法

  1. 首先:使用StaticLayout.getDesiredWidth()计算要隐藏的字宽
  2. 其次:用同样的方法计算space字符的宽度
  3. 第三名:拿到号。需要 space 秒,将第一个除以第二个。

让我们来编码:

注意:我使用了与您输入的相同的文本。

<TextView
    android:id="@+id/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="This is my sample text goes here\n with multiple words and lines and center aligned" />

Java

TextView textView = findViewById(R.id.textview);
String originalText = textView.getText().toString();
// Get the word that you want to replace
String text = originalText.substring(11, 18);
// Step 1: Get the word width
float wordWidth = StaticLayout.getDesiredWidth(text, new TextPaint());
// Step 2: Get the space width
float spaceWidth = StaticLayout.getDesiredWidth(" ", new TextPaint());
// Step 3: Get the needed no. of spaces
float nSpaces = wordWidth / spaceWidth;

// Step 4: Replace the word with the no. of spaces
StringBuilder newText = new StringBuilder(originalText.substring(0, 11));
for (int i = 0; i < nSpaces; i++) {
    newText.append(" ");
}

newText.append(originalText.substring(18));
textView.setText(newText);

结果