在 TextView 上设置文本时,在屏幕上显示文本需要很长时间

Dan*_*son 3 android textview kotlin

我将文本视图上的文本设置为长度为 14,000,000 个字符的字符串。

加载到屏幕上需要 1 到 5 分钟(取决于设备)。有什么想法可以加快速度吗?

这是相关代码:

  responseView.text = requestResponsePair.second
 .....................
  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context="com.salesrabbit.android.sales.universal.features.lumberjack.TextDisplayFragment">

 <TextView
     android:id="@+id/request_label"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="@string/request_label_string"
     android:textSize="20sp"/>

 <TextView
     android:id="@+id/text_view_request"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>

 <TextView
     android:id="@+id/response_label"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="@string/response_label_string"
     android:textSize="20sp"/>

 <TextView
     android:id="@+id/text_view_response"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>

  </LinearLayout>
Run Code Online (Sandbox Code Playgroud)

Gio*_*ous 5

方法一

最近,Google 宣布PrecomputedText可用于 SDK 级别 28 及以上版本。与此同时,它PrecomputedTextCompat已经发布,可用于 SDK 21 到 27。我还没有尝试过,但是Chris Craik发表了一篇 Medium 文章,名为“ RecyclerView 中的预取文本布局”,其中解释了如何使用它以及在不丢失任何帧的情况下,有多少工作负载从 UI 线程中脱离出来。

文章片段

预计算

val precomputedText : Spannable = PrecomputedTextCompat.create(expensiveText, params)
Run Code Online (Sandbox Code Playgroud)

将预先计算的文本设置为 TextView

TextViewCompat.setPrecomputedText(myTextView, precomputedText)
Run Code Online (Sandbox Code Playgroud)

请务必阅读文档,因为需要在后台线程中发布一些内容。

方法二

将文本分成小块或段落。将其放入列表中并使用简单的 RecyclerView 来显示列表中的每个项目。这很简单,您将免费获得良好的性能,因为 RecyclerView 将渲染和处理用户可见的项目。

另外,请务必收听Android 开发者后台播客的第 90 集:Spanspanspanspan,它是由 Android 工程团队的开发者主持的。