TextView换行居中,每行居中显示

来源:互联网 发布:淘宝助理如何添加水印 编辑:程序博客网 时间:2024/05/16 12:49

textView默认换行是顶到textview的左边的,有时候需求会要求文本中的每行都是居中的,下面的代码可实现:

public class CenterTextView extends TextView {    private StaticLayout mStaticLayout;    private TextPaint mTextPaint;    public CenterTextView(Context context) {        super(context);    }    public CenterTextView(Context context, AttributeSet attrs) {        super(context, attrs);    }    public CenterTextView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    @Override    protected void onSizeChanged(int w, int h, int oldw, int oldh) {        super.onSizeChanged(w, h, oldw, oldh);        initView();    }    private void initView() {        mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);        mTextPaint.setTextSize(getTextSize());        mTextPaint.setColor(getCurrentTextColor());        mStaticLayout = new StaticLayout(getText(), mTextPaint, getWidth(), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);    }    @Override    protected void onDraw(Canvas canvas) {        mStaticLayout.draw(canvas);    }}

0 0
原创粉丝点击