繁体   English   中英

如何真正删除(AutoResize)TextView中的填充?

[英]How to really remove the Padding in an (AutoResize)TextView?

内容

我想要一个TextView,它可以自动将其textsize调整为屏幕的宽度。 因此,我根据Chase帖子下载了AutoResizeTextView 它运行良好,有时View在设备上仍在增长或缩小,但是我可以接受。 但是,我真的很想让TextView的Padding非常有限,以最佳利用屏幕上剩余的空间。 因此,我将类扩展如下:

public class AutoResizeTextViewNoPadding extends AutoResizeTextView {

    public AutoResizeTextViewNoPadding(Context context) {
        super(context);
    }

    public AutoResizeTextViewNoPadding(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AutoResizeTextViewNoPadding(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int yOffset = getHeight() - getBaseline() - (int)super.getTextSize()/15;

        // this does not work, gives a blank view
//        int bottom = getHeight() - getBaseline() - (int)super.getTextSize()/15;
//        int top = getHeight() - bottom; // absolute number of space cut on bottom, equals top
//        canvas.clipRect(0,top,getWidth(),bottom);
//        canvas.clipRect(0, top, getWidth(), bottom, Region.Op.REPLACE);
//        super.onDraw(canvas);

        // this does not work, also gives a blank view
//        Bitmap bitmap= Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight() - 2*yOffset, Bitmap.Config.ARGB_8888);
//        Paint p = getPaint();
//        Canvas othercanvas = new Canvas();
//        othercanvas.drawBitmap(bitmap,0,0,p);
//        super.onDraw(othercanvas);

        // this works to remove the FontPadding on the bottom, but then the top gets more Padding of course
        canvas.translate(0, yOffset);
        super.onDraw(canvas);

    }
}

问题

canvas.translate将实际文本移到视图的底部(yOffset)。 但是我实际上希望从View的底部和顶部裁剪此数量(yOffset)。 如代码所示,我尝试了两种都不起作用的方法,即,我看到一个空的View,其大小与正常的(AutoResize)TextView相同。 能做到吗?

还是可以通过其他方式解决此问题? 请注意,设置负的页边距将不起作用,因为textsize的范围会很大,因此页边距也必须处于范围内。 或者我可以在(AutoResize)TextView(NoPadding)类内的某个位置设置边距?

它不是完美的,但是如果有人正在寻找相同的东西,那么它或多或少会做到这一点(对于具有android:singleLine =“ true”的AutoResizableTextViews):

public class AutoResizeTextViewNoPadding extends TextView
{
(...)
        @Override
        public int onTestSize(final int suggestedSize,final RectF availableSPace)
        {
            paint.setTextSize(suggestedSize);
            final String text=getText().toString();
            final boolean singleline=getMaxLines()==1;
            if(singleline)
            {
                textRect.bottom=(float)(paint.getFontSpacing()*.8);
                textRect.right=paint.measureText(text);
            }
        (...)
        }

@Override
protected void onDraw(Canvas canvas) {
    int yOffset = getHeight() - getBaseline() - (int)super.getTextSize()/20;
    canvas.translate(0, 2*yOffset);
    super.onDraw(canvas);
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM