Android 具有多行支持的Textview自动调整

Android 具有多行支持的Textview自动调整,android,textview,font-size,multiline,Android,Textview,Font Size,Multiline,我一直在寻找根据文本视图的大小自动调整字体的解决方案,发现了许多解决方案,但没有一个支持多行,并且能够正确地执行(不截断文本,也不考虑重力值) 是否有其他人实施了类似的解决方案 是否也可以设置如何找到最佳行数的约束?也许根据每行的最大字体大小或最大字符数?以下内容对我来说比使用基于省略号的解决方案更好 void adjustTextScale(TextView t, float max, float providedWidth, float providedHeight) { // s

我一直在寻找根据文本视图的大小自动调整字体的解决方案,发现了许多解决方案,但没有一个支持多行,并且能够正确地执行(不截断文本,也不考虑重力值)

是否有其他人实施了类似的解决方案


是否也可以设置如何找到最佳行数的约束?也许根据每行的最大字体大小或最大字符数?

以下内容对我来说比使用基于省略号的解决方案更好

void adjustTextScale(TextView t, float max, float providedWidth, float providedHeight) {

    // sometimes width and height are undefined (0 here), so if something was provided, take it ;-)
    if (providedWidth == 0f)
        providedWidth = ((float) (t.getWidth()-t.getPaddingLeft()-t.getPaddingRight()));
    if (providedHeight == 0f)
        providedHeight = ((float) (t.getHeight()-t.getPaddingTop()-t.getPaddingLeft()));

    float pix = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics());

    String[] lines = t.getText().toString().split("\\r?\\n");

    // ask paint for the bounding rect if it were to draw the text at current size
    Paint p = new Paint();
    p.setTextScaleX(1.0f);
    p.setTextSize(t.getTextSize());
    Rect bounds = new Rect();
    float usedWidth = 0f;

    // determine how much to scale the width to fit the view
    for (int i =0;i<lines.length;i++){
        p.getTextBounds(lines[i], 0, lines[i].length(), bounds);
        usedWidth = Math.max(usedWidth,(bounds.right - bounds.left)*pix);
    }

    // same for height, sometimes the calculated height is to less, so use §µ{ instead
    p.getTextBounds("§µ{", 0, 3, bounds);
    float usedHeight = (bounds.bottom - bounds.top)*pix*lines.length;

    float scaleX = providedWidth / usedWidth;
    float scaleY = providedHeight / usedHeight;

    t.setTextSize(TypedValue.COMPLEX_UNIT_PX,t.getTextSize()*Math.min(max,Math.min(scaleX,scaleY)));


}
void adjustTextScale(文本视图t、浮点最大值、浮点提供的宽度、浮点提供的高度){
//有时宽度和高度是未定义的(此处为0),因此如果提供了某些内容,请接受它;-)
如果(提供的宽度==0f)
providedWidth=((浮点)(t.getWidth()-t.getPaddingLeft()-t.getPaddingRight());
如果(提供的高度==0f)
providedHeight=((float)(t.getHeight()-t.getPaddingTop()-t.getPaddingLeft());
float pix=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,1,getResources().getDisplayMetrics());
字符串[]行=t.getText().toString().split(\\r?\\n”);
//如果要以当前大小绘制文本,请向paint请求边界矩形
油漆p=新油漆();
p、 setTextScaleX(1.0f);
p、 setTextSize(t.getTextSize());
Rect bounds=new Rect();
浮点数使用宽度=0f;
//确定缩放宽度以适应视图的大小

对于(int i=0;i之后,我问了一个类似的问题,并得到了这个问题的答案:


对于自定义行为,您需要相应地更改代码。

如果您列出您尝试过的解决方案,以及为什么每个解决方案都不适用于您以节省每个人的时间,这将很有帮助:)正如我所写的,我在这个网站上尝试了至少5种解决方案,没有一种支持多行,使用重力并正确显示文本。如果你错过了,我的建议是列出你尝试过的解决方案。我不记得我试过哪种。我至少试过5种。以下是我记得我访问过的一些链接:where is the the the the the the time代码的其余部分?我们应该在哪里调用此函数?以及“getTextBounds”中提供的字符串是什么?