34.标题换行居中的TextView

来源:互联网 发布:怎么玩转淘宝联盟 编辑:程序博客网 时间:2024/06/06 03:07

转载请注明出处 http://blog.csdn.net/qq_31715429/article/details/51373082
本文出自:猴菇先生的博客

在app中有一个展示数据的ListView,里面adapter中有标题和内容,标题居中显示。后来发现过长的标题在换行后会换行后靠左显示,不会居中。在网上找到了一个自定义TextView,可以实现换行后仍然集中显示:

package com.monkey.monkeymushroom.view;import android.content.Context;import android.graphics.Canvas;import android.graphics.Paint;import android.text.Layout.Alignment;import android.text.StaticLayout;import android.text.TextPaint;import android.util.AttributeSet;import android.widget.TextView;/** * 标题换行居中显示TextView */public class CenterTextView extends TextView {    private StaticLayout myStaticLayout;    private TextPaint tp;    public CenterTextView(Context context, AttributeSet attrs) {        super(context, attrs);    }    @Override    protected void onSizeChanged(int w, int h, int oldw, int oldh) {        super.onSizeChanged(w, h, oldw, oldh);        initView();    }    private void initView() {        tp = new TextPaint(Paint.ANTI_ALIAS_FLAG);        tp.setTextSize(getTextSize());        tp.setColor(getCurrentTextColor());        myStaticLayout = new StaticLayout(getText(), tp, getWidth(), Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);    }    @Override    protected void onDraw(Canvas canvas) {        myStaticLayout.draw(canvas);    }}
0 0