去除TextView默认内边距

今天遇到一个问题,由于TextView文本框较小,文本框内字体比较大,导致设置字体区中没有达到想要的效果,距下边比较多,记录习下解决的方法

重写TextView的Ondraw方法

public class CustomTextView extends  android.support.v7.widget.AppCompatTextView{

    private boolean adjustTopForAscent = true;
    private Paint.FontMetricsInt fontMetricsInt;

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

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

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

    @Override
    protected void onDraw(Canvas canvas) {
      //设置是否remove间距,true为remove
        if (adjustTopForAscent) {
            if (fontMetricsInt == null) {
                fontMetricsInt = new Paint.FontMetricsInt();
                getPaint().getFontMetricsInt(fontMetricsInt);
            }
            canvas.translate(0, fontMetricsInt.top - fontMetricsInt.ascent);
        }
        super.onDraw(canvas);
    }

}

设置padding内边距,自己控制文本距边框距离,达到居中效果

 <com.sam_care.view.CustomTextView
        android:gravity="center"
        android:textStyle="bold"
        android:padding="3dip"
        android:textColor="#140202"
        android:focusable="false"
        android:id="@+id/textview"
        android:layout_width="mactch_parent"
        android:layout_height="mactch_parent"
        />
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,687评论 1 92
  • 学习CSS的最佳网站没有之一 http://www.w3school.com.cn/tags/index.asp ...
    Amyyy_阅读 4,734评论 0 1
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,299评论 4 61
  • 1.块级元素和行内元素 块级(block-level)元素;行内(内联、inline-level)元素。 块元素的...
    饥人谷_小侯阅读 6,192评论 1 4
  • 没有显赫的家境,不是北京土著人,什么都需要去索取的屌丝圈圈,快乐的圈圈,带着些许无奈的圈圈! 很多政策无法改变,很...
    OO碰到OO阅读 2,444评论 0 0