当前位置:网站首页>Usage and principle of precomputedtextcompat
Usage and principle of precomputedtextcompat
2022-06-28 12:12:00 【A cup of bitter mustard】
One 、 The official introduction
Text presentation is very complicated , The features covered are : Multiple fonts 、 Row spacing 、 Space between words 、 The text direction 、 Line breaks 、 Character connection, etc . To measure and lay out a given text ,TextView A lot of work has to be done , For example, read the font file 、 Find glyphs 、 Determine the shape 、 Measure the bounding box and cache the text in the internal text cache . what's more , All this work is UI Thread , This may lead to app Frame count decrease .
We find that the time spent on text measurement takes up... Of the text settings 90%. To solve this problem , stay Android P in , And as Jetpack Part of , We have launched a new API: PrecomputedText. The API Earlier in API 14 You can pass PrecomputedTextCompat visit .
PrecomputedTextCompat Can make app You can perform the most time-consuming part of the text layout in advance, even in the background thread , To cache layout results , And return valuable measurement data . then , Can be in TextView Set the result in . such , Only about 10% Your work is left to TextView perform .
Two 、 Usage method
- compileSdkVersion No less than 28,appcompat-v7 28.0.0 or androidx appcompat 1.0.0 And above
- Use AppCompatTextView To replace TextView
- Use setTextFuture Replace setText Method
Java Example :
Future<PrecomputedTextCompat> future = PrecomputedTextCompat.getTextFuture(“text”,
textView.getTextMetricsParamsCompat(), null);
textView.setTextFuture(future);Kotlin Example :
fun AppCompatTextView.setTextFuture(charSequence: CharSequence){
this.setTextFuture(PrecomputedTextCompat.getTextFuture(
charSequence,
TextViewCompat.getTextMetricsParams(this),
null
))
}
textView.setTextFuture(“text”)3、 ... and 、 Realization principle
PrecomputedTextCompat Put time-consuming measurements into FutureTask Asynchronous execution :
@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;
}AppCompatTextView stay onMeasure Method call consumeTextFutureAndSetBlocking() when ,future.get() Blocking the thread to get the measured result . Final setText To TextView Displayed on the .
public void setTextFuture(@Nullable Future<PrecomputedTextCompat> future) {
mPrecomputedTextFuture = future;
if (future != null) {
requestLayout();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
consumeTextFutureAndSetBlocking();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private void consumeTextFutureAndSetBlocking() {
if (mPrecomputedTextFuture != null) {
try {
Future<PrecomputedTextCompat> future = mPrecomputedTextFuture;
mPrecomputedTextFuture = null;
TextViewCompat.setPrecomputedText(this, future.get());
} catch (InterruptedException | ExecutionException e) {
// ignore
}
}
}- Android 9.0 above , Use PrecomputedText Realization .
- Android 5.0~9.0, Use StaticLayout Realization .
- Android 5.0 following , Don't deal with it .
/**
* A helper class for computing text layout in background
*/
private static class PrecomputedTextFutureTask extends FutureTask<PrecomputedTextCompat> {
private static class PrecomputedTextCallback implements Callable<PrecomputedTextCompat> {
private PrecomputedTextCompat.Params mParams;
private CharSequence mText;
PrecomputedTextCallback(@NonNull final PrecomputedTextCompat.Params params,
@NonNull final CharSequence cs) {
mParams = params;
mText = cs;
}
@Override
public PrecomputedTextCompat call() throws Exception {
return PrecomputedTextCompat.create(mText, mParams);
}
}
PrecomputedTextFutureTask(@NonNull final PrecomputedTextCompat.Params params,
@NonNull final CharSequence text) {
super(new PrecomputedTextCallback(params, text));
}
}/**
* Create a new {@link PrecomputedText} which will pre-compute text measurement and glyph
* positioning information.
* <p>
* This can be expensive, so computing this on a background thread before your text will be
* presented can save work on the UI thread.
* </p>
*
* Note that any {@link android.text.NoCopySpan} attached to the text won't be passed to the
* created PrecomputedText.
*
* @param text the text to be measured
* @param params parameters that define how text will be precomputed
* @return A {@link PrecomputedText}
*/
public static PrecomputedTextCompat create(@NonNull CharSequence text, @NonNull Params params) {
Preconditions.checkNotNull(text);
Preconditions.checkNotNull(params);
try {
TraceCompat.beginSection("PrecomputedText");
// Omit the code here
// No framework support for PrecomputedText
// Compute text layout and throw away StaticLayout for the purpose of warming up the
// internal text layout cache.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
StaticLayout.Builder.obtain(text, 0, text.length(), params.getTextPaint(),
Integer.MAX_VALUE)
.setBreakStrategy(params.getBreakStrategy())
.setHyphenationFrequency(params.getHyphenationFrequency())
.setTextDirection(params.getTextDirection())
.build();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
new StaticLayout(text, params.getTextPaint(), Integer.MAX_VALUE,
Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
} else {
// There is no way of precomputing text layout on API 20 or before
// Do nothing
}
return new PrecomputedTextCompat(text, params, result);
} finally {
TraceCompat.endSection();
}
}// null on API 27 or before. Non-null on API 29 or later
private final @Nullable PrecomputedText mWrapped;
边栏推荐
- Apache2 configuration denies access to the directory, but can access the settings of the files inside
- . Net hybrid development solution 24 webview2's superior advantages over cefsharp
- 零基础C语言(一)
- JNI函数的2种书写方式
- 【vi/vim】基本使用及命令汇总
- Unity屏幕截图功能
- Which programming language will attract excellent talents?
- Leetcode 705. 设计哈希集合
- Array method in JS 2021.09.18
- Vivo手机的权限管理
猜你喜欢

【C语言】判断三角形

Join hands with cigent: group alliance introduces advanced network security protection features for SSD master firmware

Django -- MySQL database reflects the mapping data model to models

Class pattern and syntax in JS 2021.11.10

Unity屏幕截图功能

携手Cigent:群联为SSD主控固件引入高级网络安全防护特性

Day36 JS notes ecma6 syntax 2021.10.09

Web3 security serials (3) | in depth disclosure of NFT fishing process and prevention techniques

【北京航空航天大学】考研初试复试资料分享

. Net hybrid development solution 24 webview2's superior advantages over cefsharp
随机推荐
Why do many people want to change careers as programmers, while some programmers want to change careers as others?
Self use demo of basic component integration of fluent
什么是数据合规?怎样做到数据合规?
【C语言】二叉树的实现及三种遍历
AcWing 609. Salary (implemented in C language)
【vi/vim】基本使用及命令汇总
. Net hybrid development solution 24 webview2's superior advantages over cefsharp
KDD 2022 | 图“预训练、提示、微调”范式下的图神经网络泛化框架
JNI函数的2种书写方式
Timestamp and date conversion "suggested collection"
Android应用安全之JNI混淆
What method is required for word, PDF and txt files to realize full-text content retrieval?
Day32 JS note event (Part 1) September 27, 2021
Simple understanding of ThreadLocal
如何获取泛型的类型
【C语言】结构体嵌套二级指针的使用
Day31 JS notes DOM 2021.09.26
QML control type: tabbar
Vivo手机的权限管理
Ali three sides: what is the difference between using on or where in the left join associated table and the condition