簡體   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