简体   繁体   English

在android TextView中格式化长段落

[英]Formatting long paragraphs in android TextView

I have a lot of text (more than 10000 words) which I would like to display on my android app.我有很多文本(超过 10000 字),我想在我的 android 应用程序上显示它们。 The text contains bullets, paragraphs and line breaks.文本包含项目符号、段落和换行符。 I want to know how can I display on my app without manual editing.我想知道如何在没有手动编辑的情况下在我的应用程序上显示。 It is not possible to convert every line break to \\n and every tab to \\t .不可能将每个换行符都转换为\\n并将每个制表符都转换为\\t I have also tried parsing data in HTML and then using Html.fromHtml(getString(R.string.text)) .我也尝试过解析 HTML 中的数据,然后使用Html.fromHtml(getString(R.string.text)) However, the display that I get looks completely unformatted.但是,我得到的显示看起来完全没有格式化。

This is how I want the text to look like in the app:这就是我希望文本在应用程序中的外观:

HTML tags are easy solutions for simple problems, like making a text bold, italic, or even displaying bullet points. HTML 标签是简单问题的简单解决方案,例如将文本设为粗体、斜体,甚至显示项目符号。 To style text containing HTML tags, call Html.fromHtml method.要为包含 HTML 标签的文本设置样式,请调用 Html.fromHtml 方法。 Under the hood, the HTML format is converted into spans.在幕后,HTML 格式被转换为跨度。 Please note that the Html class does not support all HTML tags and CSS styles like making the bullet points another color.请注意,Html 类不支持所有 HTML 标签和 CSS 样式,例如将项目符号设为另一种颜色。

val text = "My text <ul><li>bullet one</li><li>bullet two</li></ul>"
txtview.text = Html.fromHtml(text)

Spans allow you to implement multi-style text with finer-grained customization. Span 允许您使用更细粒度的自定义来实现多样式文本。 For example, you can define paragraphs of your text to have a bullet point by applying a BulletSpan.例如,您可以通过应用 BulletSpan 将文本的段落定义为具有项目符号点。 You can customize the gap between the text margin and the bullet and the color of the bullet.您可以自定义文本边距和项目符号之间的间隙以及项目符号的颜色。 Starting with Android P, you can even set the radius of the bullet point.从 Android P 开始,您甚至可以设置项目符号点的半径。 You can also create a custom implementation for the span.您还可以为跨度创建自定义实现。 Check out the "Create custom spans" section below to find out how.查看下面的“创建自定义跨度”部分以了解如何操作。

val spannable = SpannableString("My text \nbullet one\nbullet two")
spannable.setSpan(
   BulletPointSpan(gapWidthPx, accentColor),/* start index */ 9, /* end index */ 18,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
   spannable.setSpan(BulletPointSpan(gapWidthPx, accentColor),/* start index */ 20, /* end index */ spannable.length,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
 txtview.text = spannable

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM