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); } }