gpt4 book ai didi

android - 动态调整textview的字体大小

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:07:25 24 4
gpt4 key购买 nike

是否可以根据屏幕分辨率在 TextView 中动态调整字体大小?如果是如何?我正在从 mdpi avd 开发。但是当应用程序安装在 hdpi 上时,文本显得太小。

最佳答案

使用textSize缩放像素 sp 单位是 alextsc 所暗示的。

如果你真的想要动态并让你的字体尽可能大以填充宽度,那么可以使用 textWatcher 来呈现文本并检查大小,然后动态调整字体。

以下是相当具体的,因为我在线性布局中有多个 TextView ,这只会在其中一个文本不适合时将文本调整得更小。不过,它会给你一些有用的东西。

class LineTextWatcher implements TextWatcher {

static final String TAG = "IpBike";
TextView mTV;
Paint mPaint;

public LineTextWatcher(TextView text) {
mTV = text;
mPaint = new Paint();
}

public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}

public void onTextChanged(CharSequence s, int start, int before, int count) {
}

public void afterTextChanged(Editable s) {
// do the work here.
// we are looking for the text not fitting.
ViewParent vp = mTV.getParent();
if ((vp != null) && (vp instanceof LinearLayout)) {
LinearLayout parent = (LinearLayout) vp;
if (parent.getVisibility() == View.VISIBLE) {
mPaint.setTextSize(mTV.getTextSize());
final float size = mPaint.measureText(s.toString());
if ((int) size > mTV.getWidth()) {
float ts = mTV.getTextSize();
Log.w(TAG, "Text ellipsized TextSize was: " + ts);
for (int i = 0; i < parent.getChildCount(); i++) {
View child = parent.getChildAt(i);
if ((child != null) && (child instanceof TextView)) {
TextView tv = (TextView) child;
// first off we want to keep the verticle
// height.
tv.setHeight(tv.getHeight()); // freeze the
// height.

tv.setTextSize(TypedValue.COMPLEX_UNIT_PX,
tv.getTextSize() - 1);
} else {
Log.v(TAG, "afterTextChanged Child not textView");
}
}
}
}
} else {
Log.v(TAG, "afterTextChanged parent not LinearLayout");
}
}
}

关于android - 动态调整textview的字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8478282/

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