【发布时间】:2020-11-13 15:03:27
【问题描述】:
我有一个 android textview,我正在为它设置 10 个单词的句子。
现在,我需要删除一个单词(比如第 4 个单词)而不影响剩余单词的位置/对齐方式。
请参考下图。另请注意,如果用空格替换该特定单词,则剩余单词的对齐方式仍会略有变化,因为每个字符采用不同的宽度。
如何使用 textview 实现它?任何帮助深表感谢。谢谢。
【问题讨论】:
标签: java android textview alignment
我有一个 android textview,我正在为它设置 10 个单词的句子。
现在,我需要删除一个单词(比如第 4 个单词)而不影响剩余单词的位置/对齐方式。
请参考下图。另请注意,如果用空格替换该特定单词,则剩余单词的对齐方式仍会略有变化,因为每个字符采用不同的宽度。
如何使用 textview 实现它?任何帮助深表感谢。谢谢。
【问题讨论】:
标签: java android textview alignment
您可以使用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
【讨论】:
这是一个算法
StaticLayout.getDesiredWidth()计算你想要隐藏的单词的宽度让我们编码:
注意:我使用的文字与您输入的相同。
<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);
结果
【讨论】: