【问题标题】:Android TextView multiline has extra spaceAndroid TextView 多行有额外空间
【发布时间】:2023-03-20 08:52:01
【问题描述】:

带有android:layout_width="wrap_content" 的多行文本视图会自动占用最大空间,就像它们变成match_parent 一样。有没有办法保持真正的wrap_content 行为?

示例 xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/rounded_bg"
        android:backgroundTint="@color/colorAccent"
        android:text="Example text"
        android:textAlignment="center"
        android:textColor="#fff"
        android:textSize="28sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/rounded_bg"
        android:backgroundTint="@color/colorAccent"
        android:text="Example text ================"
        android:textAlignment="center"
        android:textColor="#fff"
        android:textSize="28sp" />

    <TextView
        android:layout_width="270dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/rounded_bg"
        android:backgroundTint="@color/colorAccent"
        android:text="Example text ================"
        android:textAlignment="center"
        android:textColor="#fff"
        android:textSize="28sp" />

</LinearLayout>

  1. 单行
  2. 多行
  3. 我希望它看起来如何

我想删除多行文本左右两端的多余空格。如果我手动将layout_width 设置为270dp 之类的特定值,则可以完成效果,但随后它变得任意。我更喜欢将其保留为wrap_content

编辑: 这样做的目的是我想使用适合文本的自定义背景、圆形背景。我已经编辑了示例 xml 和图像。

【问题讨论】:

标签: android textview


【解决方案1】:

在 .java 文件中以编程方式尝试,无需更改 xml 文件

SpannableString s = new SpannableString("your content");             
s.setSpan(new BackgroundColorSpan(getResources().getColor(R.color.colorAccent)), 0, s.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);                     
text.setText(s);

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
  • 这几乎就是我要找的。但我已经编辑了我的问题,以澄清我想要整个文本的圆形背景。
猜你喜欢
  • 2019-08-19
  • 2016-02-08
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多