Android TextView左右對齊

來源:互聯網
上載者:User

標籤:

Android中的TextView控制項預設是做不到左右對齊的,都是靠左對齊。可能的原因是安卓預設數字、字母不能為第一行以後每行的開頭字元,因為數字、字母為半形字元,還有就是文字中的英文字元佔用1個位元組,而一個漢字佔用兩個位元組。下面我就介紹下實現左右對齊的原理:
1、測量一個中文漢字所佔用的寬度
2、根據TextView的寬度和一個漢字所佔用的寬度以及字元之間的間隔計算出總行數。
3、根據padding和margin以及行高計算出TextView的總高度。
4、繪製每一行的每一個字元
效果如下:

具體代碼如下:

package com.wedroid.framework.module.ui;import android.content.Context;import android.graphics.Canvas;import android.graphics.Paint;import android.text.TextPaint;import android.text.TextUtils;import android.util.AttributeSet;import android.view.ViewGroup.MarginLayoutParams;import android.view.ViewTreeObserver.OnPreDrawListener;import android.widget.TextView;public class WeDroidAlignTextView extends TextView {    private boolean first = true;    public WeDroidAlignTextView(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);        getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {            @Override            public boolean onPreDraw() {                initTextInfo();                return true;            }        });    }    public WeDroidAlignTextView(Context context, AttributeSet attrs) {        this(context, attrs, 0);    }    public WeDroidAlignTextView(Context context) {        this(context, null, 0);    }    private float textSize;    private float textLineHeight;    private int top;    private int y;    private int lines;    private int bottom;    private int right;    private int left;    private int lineDrawWords;    private char[] textCharArray;    private float singleWordWidth;    private float lineSpacingExtra;    public void initTextInfo() {        textSize = getTextSize();        textLineHeight = getLineHeight();        left = 0;        right = getRight();        y = getTop();        // 要畫的寬度        int drawTotalWidth = right - left;        String text = getText().toString();        if (!TextUtils.isEmpty(text) && first) {            textCharArray = text.toCharArray();            TextPaint mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);            mTextPaint.density = getResources().getDisplayMetrics().density;            mTextPaint.setTextSize(textSize);            // 一個單詞的的寬度            singleWordWidth = mTextPaint.measureText("一") + lineSpacingExtra;            // 一行可以放多少個字元            lineDrawWords = (int) (drawTotalWidth / singleWordWidth);            int length = textCharArray.length;            lines = length / lineDrawWords;            if ((length % lineDrawWords) > 0) {                lines = lines + 1;            }            first = false;            MarginLayoutParams layoutParams = (MarginLayoutParams) getLayoutParams();            int totalHeight = (int) (lines*textLineHeight+textLineHeight*2 + getPaddingBottom()+getPaddingTop()+layoutParams.bottomMargin+layoutParams.topMargin);            setHeight(totalHeight);        }    }    @Override    protected void onDraw(Canvas canvas) {        bottom = getBottom();        int drawTotalLine = lines;        if(maxLine!=0&&drawTotalLine>maxLine){            drawTotalLine = maxLine;        }        for (int i = 0; i < drawTotalLine; i++) {            try {                int length = textCharArray.length;                int mLeft = left;                // 第i+1行開始的字元index                int startIndex = (i * 1) * lineDrawWords;                // 第i+1行結束的字元index                int endTextIndex = startIndex + lineDrawWords;                if (endTextIndex > length) {                    endTextIndex = length;                    y += textLineHeight;                } else {                    y += textLineHeight;                }                for (; startIndex < endTextIndex; startIndex++) {                    char c = textCharArray[startIndex];//                  if (c == ‘ ‘) {//                      c = ‘\u3000‘;//                  } else if (c < ‘\177‘) {//                      c = (char) (c + 65248);//                  }                    canvas.drawText(String.valueOf(c), mLeft, y, getPaint());                    mLeft += singleWordWidth;                }            } catch (Exception e) {                e.printStackTrace();            }        }    }    int maxLine;    public void setMaxLines(int max){        this.maxLine = max;    }    public void setLineSpacingExtra(int lineSpacingExtra){        this.lineSpacingExtra = lineSpacingExtra;    }     /**      * 判斷是否為中文      * @return      */      public static boolean containChinese(String string){          boolean flag = false;          for (int i = 0; i < string.length(); i++) {              char c = string.charAt(i);              if ((c >= 0x4e00) && (c <= 0x9FA5)) {                  flag = true;              }          }          return flag;      }    public static String ToDBC(String input) {        // 導致TextView異常換行的原因:安卓預設數字、字母不能為第一行以後每行的開頭字元,因為數字、字母為半形字元        // 所以我們只需要將半形字元轉換為全形字元即可        char c[] = input.toCharArray();        for (int i = 0; i < c.length; i++) {            if (c[i] == ‘ ‘) {                c[i] = ‘\u3000‘;            } else if (c[i] < ‘\177‘) {                c[i] = (char) (c[i] + 65248);            }        }        return new String(c);    }}

Android TextView左右對齊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.