Android(安卓)PrecomputedTextCompat
16lz
2022-04-01
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真正展示出来的时间差去做耗时操作。
更多相关文章
- Android中的多种文件读写操作方法
- Android(安卓)检测用户一段时间无操作
- Android(安卓)封装的数据库管理操作类
- android最近任务列表,删除某个应用操作
- Android使用Linux命令执行文件操作
- Android中的线程模型
- Android中CheckBox复选框操作
- Android(安卓)SQLite数据库相关操作
- 【Java转Android】30. LitePal操作SQLite数据库