gpt4 book ai didi

android - TextView.onDraw 导致死循环

转载 作者:行者123 更新时间:2023-11-29 14:57:19 25 4
gpt4 key购买 nike

我想要一个调整字体大小的 TextView,以便 View 中的文本自动扩展(或收缩)以填充 View 的整个宽度。我想我可以通过创建一个自定义的 TextView 来做到这一点,它覆盖 onDraw() 如下:

public class MaximisedTextView extends TextView {
// (calls to super constructors here...)

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);

TextPaint textPaint = this.getPaint();
Rect bounds = new Rect();

String text = (String)this.getText(); // current text in view
float textSize = this.getTextSize(); // current font size
int viewWidth = this.getWidth() - this.getPaddingLeft() - this.getPaddingRight();
textPaint.getTextBounds(text, 0, text.length(), bounds);
int textWidth = bounds.width();

// reset font size to make text fill full width of this view
this.setTextSize(textSize * viewWidth/textWidth);
}
}

但是,这会使应用程序陷入无限循环(文本大小每次都会略微增大和缩小!),所以我显然采用了错误的方式。对 setTextSize() 的调用是否会触发无效,以便无休止地再次调用 onDraw?

有什么方法可以阻止递归调用(如果发生这种情况)?还是我应该以完全不同的方式进行处理?

最佳答案

Does the call to setTextSize() trigger an invalidate so that onDraw is called again, endlessly?

是的,这可能就是正在发生的事情。如果你take a look of the source code setTextSize 你会看到它会调用这个方法:

private void setRawTextSize(float size) {
if (size != mTextPaint.getTextSize()) {
mTextPaint.setTextSize(size);

if (mLayout != null) {
nullLayouts();
requestLayout();
invalidate(); // yeahh... invalidate XD
}
}
}

所以,如果您正在努力覆盖 onDraw 方法,为什么不直接使用一些 drawText 呢? Canvas 的方法类(class)?

关于android - TextView.onDraw 导致死循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3207414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com