我有一个方形的 FrameLayout。我在布局内有一个 TextView,并为用户提供了增加/减少 textSize 的选项。当文本大到足以填充整个 FrameLayout 时,我想限制文本增加选项。因此,如果我从 25sp 之类的东西开始,当用户达到 40sp 并且 TextView 高度超过 FrameLayout 高度时,我需要恢复到 39sp 并禁止进一步增加文本大小。 TextView的来源是spannable。
到目前为止,我是这样做的。
在增加按钮上,我只需为每个可跨越的 fragment setTextSize(currentValue + 1)
;
因为当我再次设置Text时我不知道TextView的“真实”大小,所以我使用了
ViewTreeObserver vto = textView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//here I have the real sizes of the textView and if the height is too big, I simply
setTextSize(currentValue - 1)
}
缺点是增加文本 -> 再次减少文本的可见操作。因此,用户会在大约 100 毫秒内看到文本变大,然后又恢复原状。 有没有一种好的方法来处理这个计算,这样我就可以避免实际增加文本大小?
最佳答案
我建议在实际更改大小之前使用 TextPaint 和 span 类来测量文本。测量文本需要将其分割成跨度。然后,您应该将跨度应用于 TextPaint 对象并询问其文本 block 尺寸。
http://developer.android.com/reference/android/text/TextPaint.html http://developer.android.com/reference/android/graphics/Paint.FontMetrics.html http://developer.android.com/reference/android/text/style/CharacterStyle.html
任务相当复杂,因此如果遇到任何麻烦,请随时寻求更多帮助。我用来测量文本的代码很长并且没有注释,因此我可能会将其发布到谷歌代码以备不时之需。
关于android - 使 TextView 适合 Android 上的 Layout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15087110/