当前位置:网站首页>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;
边栏推荐
- Class pattern and syntax in JS 2021.11.10
- MapReduce项目案例3——温度统计
- Redis hash hash type string (5)
- day25 js中的预解析、递归函数、事件 2021.09.16
- Zero basic C language (I)
- SoapUI rookie tutorial
- Apache2 configuration denies access to the directory, but can access the settings of the files inside
- Graphics view framework for QT learning (to realize startup animation)
- Unity屏幕截图功能
- Software test interview classic + 1000 high-frequency real questions, and the hit rate of big companies is 80%
猜你喜欢

The default point of this in JS and how to modify it to 2021.11.09

Unity screenshot function

day32 js笔记 事件(上)2021.09.27

Multi dimensional monitoring: the data base of intelligent monitoring

JS foundation 8

【C语言】结构体嵌套二级指针的使用

Deployment and optimization of vsftpd service

Swin, three degrees! Eth open source VRT: a transformer that refreshes multi domain indicators of video restoration

Necessary for beginners PR 2021 quick start tutorial, PR green screen matting operation method

Day32 JS note event (Part 1) September 27, 2021
随机推荐
RemoteViews的作用及原理
Unity screenshot function
FTP protocol for Wireshark packet capture analysis
AGCO AI frontier promotion (2.16)
【C语言】如何产生正态分布或高斯分布随机数
Data analysis learning notes
. Net hybrid development solution 24 webview2's superior advantages over cefsharp
Redis hash hash type string (5)
AcWing 608. Poor (implemented in C language)
fatal: unsafe repository (‘/home/anji/gopath/src/gateway‘ is owned by someone else)
Web3 security serials (3) | in depth disclosure of NFT fishing process and prevention techniques
Bisection (integer bisection and floating point bisection)
【C语言】文件读写函数使用
Day36 JS notes ecma6 syntax 2021.10.09
Interview skills for interview steps
Connectionreseterror: [winerror 10054] the remote host forced an existing connection to be closed
Dongyuhui, New Oriental and Phoenix Satellite TV
Is it safe to buy stocks and open an account on the account QR code of the CICC securities manager? Ask the great God for help
Cannot redeclare block range variables
如何获取泛型的类型