如何让TextView显示多行文本?

11

我想通过TextView和strings.xml来显示多行文本。我希望在页面中间之前显示前几行,其他行完整显示在页面上。我希望前几行的宽度与页面相同。

页面左侧是一张图片,右侧是我的句子。

这是我的代码,但显示效果很混乱。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<ImageView 
    android:id="@+id/logoImage"
    android:src="@drawable/ic_launcher"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
<TextView
    android:id="@+id/txtIntroduce"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/txtIntroduce"
    android:textColor="@color/blue_text"
    android:background="@color/blue"/>
</LinearLayout>

字符串.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <string name="intro">.................  ....</string>
<resources>

我该如何展示这个视图? 抱歉我的英语不好,感谢你的帮助。


据我所知,您将不得不使用多个TextView来实现您想要的目标。 - Rachit Mishra
5个回答

25

你可以查看TextView的这三个XML属性:

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:ellipsize="end"
    android:maxLines="5"
    android:singleLine="false" />

在那里,您可以定义 TextView 应具有多少行以及当文本超出 TextView 大小时是否应显示点号("...")。

此外,您可以在 .xml 文件中使用return来开始一个新行:("\n")

<string name="intro">This is the first line \n this is a new line.</string>

但是当我使用这段代码时,我的文本在不同密度和尺寸的移动设备上显示效果不佳。我想这是真的吗? - SensorS

5

您想让文本环绕图片,就像这样:

--------------------
|..........| xxxxxxx
|..Picture.| xxxxxxx
|..........| xxxxxxx
------------ xxxxxxx
xxxxxxxxxxTextxxxxxx
xxxxxxxxxxxxxxxxxxxx

我认为最简单的选择是使用WebView。然而,根据这篇文章,您也可以在TextView中使用图像标签。我自己从未尝试过,但我已经使用了其他标签,例如:TextView.setText(Html.fromHtml("<b>一些粗体文字</b> 一些普通文本")),因此在您的情况下可能会有类似的效果。


谢谢。确切地说,我想展示一个类似的视图,但是当我使用WebView时,我应该展示一个互联网上的网页,这是正确的吗?你的链接对我来说无效(404错误)。请更详细地解释一下。谢谢。 - SensorS
原始链接已修复。我认为研究这些问题会比我解释更有帮助:https://dev59.com/f3A65IYBdhLWcg3wyh97 和 https://dev59.com/90zSa4cB1Zd3GeqPoais#12971408 。那里有很多选项。 - Merk

3

这是我在stackoverflow上的第一篇文章...

我认为这是在Android上拥有多行文本视图的最佳简单方法。请看以下步骤:

  1. 使用外部编辑器(例如Microsoft Word,LibreOffice等)编写带有段落和多行的文本。

  2. 打开项目的strings.xml文件并创建一个新字符串(例如<string name="my_multiline_textview></string>

  3. 从您的文本中复制每个段落并将其粘贴到标签内,在末尾放置\n

  4. 您在段落末尾放置的\n越多,它们之间的行数就越多。

  5. 在布局中插入一个新的textView,并将其与步骤2、3和4中创建的多行字符串相关联(android:text="@string/my_multiline_textview")。

  6. 返回Graphical Layout并看到神奇的事情发生了 :-)

希望这些信息能对大家有所帮助。再见。


3

更改行数和限制字符数量

android:inputType="textMultLine"
android:maxLength="180"
android:lines="5"
android:maxLines="5"


1
虽然这段代码可能有效,但你应该添加一些描述其原因的文本。 - nbryans
它正在工作。这就是我要找的。谢谢。我设置了maxWidth="100dp"。 - Nabeel K

2
你需要这4个属性:
  1. android:layout_width (设置一个值,比如300dp)
  2. android:ellipsize="end"
  3. android:maxLines="你想要的行数"
  4. android:singleLine="false"
例如: enter image description here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接