【问题标题】:How to delete one word from a android textview (multiple lines) without affecting the alignment/position of other words如何从android textview(多行)中删除一个单词而不影响其他单词的对齐/位置
【发布时间】:2020-11-13 15:03:27
【问题描述】:

我有一个 android textview,我正在为它设置 10 个单词的句子。

现在,我需要删除一个单词(比如第 4 个单词)而不影响剩余单词的位置/对齐方式。

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

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

【问题讨论】:

    标签: java android textview alignment


    【解决方案1】:

    您可以使用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

    【讨论】:

    • 我可以将颜色设置为透明吗? ,在我的实际情况中,我有一张背景图片。
    • @John - 有一个 Color.TRANSPARENT,所以这应该是可能的
    【解决方案2】:

    这是一个算法

    1. 首先:使用StaticLayout.getDesiredWidth()计算你想要隐藏的单词的宽度
    2. 第二:用同样的方法计算空格字符的宽度。
    3. 第三: 拿下。通过将第一个除以第二个来获得所需的空间。

    让我们编码:

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

    <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);
    

    结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 2018-03-29
      • 2017-06-14
      • 1970-01-01
      • 2014-04-20
      相关资源
      最近更新 更多