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();
}
希望能帮助到大家。