Android TextView 不同主题下两边对齐

来源:互联网 发布:天敏t2网络机顶盒 编辑:程序博客网 时间:2024/05/15 08:09


问题描述

这两天遇到了一个TextView字体对齐的问题,就是两个汉字,三个汉字和四个汉字对齐的问题,之前我采用的方法是用空格(使用\t是不可行的)或者两个字与四个字对齐时使用全角中文打空格,但是三个字就不好对齐,所以最后我选择了空格,但现在出现一个问题是Android主题修改的问题,有的主题自带的字体所占据宽度的是不一样的,导致本应该对齐的而无法对齐。

解决方法

这种情况要做各个屏幕和主题适配工作,解决方法是自定义TextView,比如:平均间距 =(四个字的宽度-两个字的宽度)/ (2-1)然后设置每个字的间距为平均间距:

public class JustifyTextView extends TextView {    private int mLineY;    private float mViewWidth = 0;    public JustifyTextView(Context context, AttributeSet attrs) {        super(context, attrs);    }    @Override    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {        super.onLayout(changed, left, top, right, bottom);    }    @Override    protected void onDraw(Canvas canvas) {        TextPaint paint = getPaint();        paint.setColor(getCurrentTextColor());        paint.drawableState = getDrawableState();        String text = (String) getText();        mLineY = 0;        mLineY += getTextSize();        float width = StaticLayout.getDesiredWidth(text, 0, text.length(), getPaint());        drawScaledText(canvas, text, width);        Paint.FontMetrics fm = paint.getFontMetrics();        int textHeight = (int) fm.top;        mLineY += textHeight;    }    private void drawScaledText(Canvas canvas, String line, float lineWidth) {        float x = 0;        float d = (mViewWidth - lineWidth) / (line.length() - 1);        for (int i = 0; i < line.length(); i++) {            String c = String.valueOf(line.charAt(i));            float cw = StaticLayout.getDesiredWidth(c, getPaint());            canvas.drawText(c, x, mLineY, getPaint());            x += cw + d;        }    }    public void setTitleWidth( TextView tv ){        String text = (String) tv.getText();        float width = StaticLayout.getDesiredWidth(text, 0, text.length(), tv.getPaint());        mViewWidth = width;        setWidth((int) mViewWidth);        invalidate();    }}
在使用的地方这样使用:

<com.yitu8.client.application.views.JustifyTextView                        android:id="@+id/tv_hb"                        android:layout_width="wrap_content"                        android:layout_height="wrap_content"                        android:layout_marginLeft="30dp"                        android:text="航班"                        android:textColor="@color/home_text"                        android:textSize="@dimen/font_14_size"                         />
在组件中调用setTitleWith()将宽度设置成较长的标题:

tv_hb.setTitleWidth(tv_ycsj);tv_mdd.setTitleWidth(tv_ycsj);




0 0
原创粉丝点击