Android PrecomputedTextCompat

官方文档:https://developer.android.com/reference/androidx/core/text/PrecomputedTextCompat

官方视频:https://www.youtube.com/watch?v=x-FcOX6ErdI

Related Blog:https://medium.com/mindorks/precomputedtext-new-api-in-android-pie-74eb8f420ee6

2018的Google IO上提出了这样一个异步处理text的API,可以帮助我们提升textview的展示效率

以往我们在setText的时候会立刻去执行很多耗时操作比如rendering,measure,textwatcher等等。但我们有时候并不想立刻去做这些事情,setText的时候并不意味着我们的textview立刻就要展示到屏幕上。

PrecomputedText给我们提供了一种机制,可以将90%以上的测量等耗时操作放到一个异步线程中去完成。API28以上直接支持,API21-27利用text layout cache去实现,API20以下的不做操作。

val params: PrecomputedText.Params = textView.getTextMetricsParams()val ref = WeakReference(textView)executor.execute {    // background thread    val text = PrecomputedText.create("Hello", params)    val textView = ref.get()    textView?.post {        // UI thread        val textViewRef = ref.get()        textViewRef?.text = text    }}

另一种通过future的方式调用,textView会在onMeasure之前block住等待future的计算结果。setTextFuture方法需要使用AppCompatTextView

textView.setTextFuture(PrecomputedTextCompat.getTextFuture(message.getBody(),      TextViewCompat.getTextMetricsParams(textView),        /*optional custom executor*/ null));

PrecomputedTextCompat.getTextFuture方法:

@UiThreadpublic static Future<PrecomputedTextCompat> getTextFuture(        @NonNull final CharSequence charSequence, @NonNull PrecomputedTextCompat.Params params,        @Nullable Executor executor) {    PrecomputedTextFutureTask task = new PrecomputedTextFutureTask(params, charSequence);    if (executor == null) {        synchronized (sLock) {            if (sExecutor == null) {                sExecutor = Executors.newFixedThreadPool(1);            }            executor = sExecutor;        }    }    executor.execute(task);    return task;}

在RecyclerView中,如果我们开启了preFetch功能,这时候使用这种方式会提高我们的效率,它能够充分利用preFetch和view真正展示出来的时间差去做耗时操作。

更多相关文章

  1. Android中的多种文件读写操作方法
  2. Android(安卓)检测用户一段时间无操作
  3. Android(安卓)封装的数据库管理操作类
  4. android最近任务列表,删除某个应用操作
  5. Android使用Linux命令执行文件操作
  6. Android中的线程模型
  7. Android中CheckBox复选框操作
  8. Android(安卓)SQLite数据库相关操作
  9. 【Java转Android】30. LitePal操作SQLite数据库

随机推荐

  1. 疫情来袭,30分钟学会用python开发部署疫情
  2. 经历 | 寒冷的冬季,三本苦逼的找实习之路
  3. linux 复习
  4. 【TensorFlow】使用迁移学习训练自己的模
  5. 十分钟学会reqests模块爬取数据——从爬
  6. 购买并在自己的云服务器上配置anaconda
  7. GitHub上3k+star的python爬虫库你了解吗?
  8. Flutter | 什么是 Flutter?(送书)
  9. 怎么样描述你的数据——用python做描述性
  10. 手机上利用python进行数据分析——创建自