1. 程式人生 > >Android TextView 去除內邊距

Android TextView 去除內邊距

Android開發的小夥伴們,可能經常會遇到這樣的問題。當UI的給出設計圖的時候,一般說字的大小為XX個畫素。

由於TextView總是會自動為我們的字型大小加上一個內邊距影響佈局效果,現在就用幾行程式碼搞定這個問題。

 public NoPaddingTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setGravity(Gravity.CENTER_VERTICAL);
        setIncludeFontPadding(false);
        int height = getViewHeight(this);

        int textSize = (int) getTextSize() + 1;
        int padding = (int) (height - getTextSize());
        if (height / 2 == 0 && textSize % 2 == 0) {
            setPadding(0, -padding, 0, -padding);
        } else {
            padding -= 1;
            setPadding(0, -padding, 0, -padding);

        }


    }

    public static int getViewHeight(View view) {
        int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(width, height);
        return view.getMeasuredHeight();
    }
希望能幫助到大家。