Android PrecomputedTextCompat

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方法:

@UiThread
public 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)