TextView 實現自動換行 – Android移動開發技術文章_手機開發 Android移動開發教學課程

package com.liao.intentservice; 
 
import java.util.Arrays; 
 
import android.content.Context; 
import android.content.res.Resources; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.graphics.Paint.FontMetrics; 
import android.graphics.Paint.Style; 
import android.util.AttributeSet; 
import android.util.TypedValue; 
import android.view.View; 
 
 
public class AutoText extends View { 
    private Paint mPaint = new Paint(); 
 
    public AutoText(Context context) { 
        this(context,null); 
    } 
 
     
    public AutoText(Context context, AttributeSet attrs, int defStyle) { 
        super(context, attrs, defStyle); 
        init(); 
    } 
 
    public AutoText(Context context, AttributeSet attrs) { 
        this(context,attrs,0); 
    } 
 
    private void init() { 
        mPaint.setAntiAlias(true); 
        mPaint.setColor(Color.RED);  
        mPaint.setStyle(Style.STROKE); 
        mPaint.setTextSize(getRawSize(TypedValue.COMPLEX_UNIT_DIP, 15)); 
         
    } 
 
    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
        super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
         
         
//      setMeasuredDimension(300, 200); 
    } 
     
    @Override 
    protected void onDraw(Canvas canvas) { 
        super.onDraw(canvas); 
         
        //view.draw()繪制瞭控件的背景 
         
        //控件的繪制操作及順序: 
        /*
         * Draw traversal performs several drawing steps which must be executed
         * in the appropriate order:
         *
         *      1. Draw the background  (繪制控件設置的背景)
         *      2. If necessary, save the canvas' layers to prepare for fading  
         *      3. Draw view's content  (可以重寫, onDraw(canvas);)
         *      4. Draw children      (可重寫,用來分發畫佈到子控件,具體看ViewGroup。對應方法dispatchDraw(canvas);此方法依次調用瞭子控件的draw()方法)
         *      5. If necessary, draw the fading edges and restore layers (繪制控件四周的陰影漸變效果)
         *      6. Draw decorations (scrollbars for instance) (用來繪制滾動條,對應方法onDrawScrollBars(canvas);。
         *      可以重寫onDrawHorizontalScrollBar()和onDrawVerticalScrollBar()來自定義滾動條)
         */ 
         
        //可以繪制內容和滾動條。 
         
        //draw backgroud 
        canvas.drawColor(Color.WHITE); 
         
        //draw text 
        FontMetrics fm = mPaint.getFontMetrics(); 
         
        float baseline = fm.descent – fm.ascent;  
        float x = 0; 
        float y =  baseline;  //由於系統基於字體的底部來繪制文本,所有需要加上字體的高度。 
         
        //String txt = getResources().getString("asda"); 
        String txt = "計算機科學或相關專業領域的本科及以上學歷, 並有2年以上相關工作經驗;2、在計算機技術領域擁有紮實的技術功底,尤其在數據結構、算法和代碼、軟件設計方面功力深厚;" + 
                "+3、熟悉分佈式計算、網絡系統設計,數據庫設計和大規模存儲系統,嫻熟的C/C++編程技巧"+ 
                "4、熟悉HTTP協議,開發基於HTTP協議的應用;有聯網應用、聯網遊戲開發經驗者優先"+ 
"5、具備Web service/Ajax/JavaScript/Apache/Tomcat/Struts/iBatis/Spring/PHP/JSP/Python等方面經驗者優先考慮;"+ 
"6、熟悉TCP/IP協議,熟悉socket和多線程開發,具備高訪問量網絡開發工作經驗。"; 
         
        //文本自動換行 
        String[] texts = autoSplit(txt, mPaint, getWidth() – 5); 
         
        System.out.printf("line indexs: %s\n", Arrays.toString(texts)); 
         
        for(String text : texts) {  
            canvas.drawText(text, x, y, mPaint);  //坐標以控件左上角為原點 
            y += baseline + fm.leading; //添加字體行間距 
        } 
    } 
     
     
    /**
     * 自動分割文本
     * @param content 需要分割的文本
     * @param p  畫筆,用來根據字體測量文本的寬度
     * @param width 指定的寬度
     * @return 一個字符串數組,保存每行的文本
     */ 
    private String[] autoSplit(String content, Paint p, float width) { 
        int length = content.length(); 
        float textWidth = p.measureText(content); 
        if(textWidth <= width) { 
            return new String[]{content}; 
        } 
         
        int start = 0, end = 1, i = 0; 
        int lines = (int) Math.ceil(textWidth / width); //計算行數 
        String[] lineTexts = new String[lines]; 
        while(start < length) { 
            if(p.measureText(content, start, end) > width) { //文本寬度超出控件寬度時 
                lineTexts[i++] = (String) content.subSequence(start, end); 
                start = end; 
            } 
            if(end == length) { //不足一行的文本 
                lineTexts[i] = (String) content.subSequence(start, end); 
                break; 
            } 
            end += 1; 
        } 
        return lineTexts; 
    } 
     
    /**
     * 獲取指定單位對應的原始大小(根據設備信息)
     * px,dip,sp -> px
     * 
     * Paint.setTextSize()單位為px
     * 
     * 
     * 
     * 代碼摘自:TextView.setTextSize()
     * 
     * @param unit  TypedValue.COMPLEX_UNIT_*
     * @param size
     * @return
     */ 
    public float getRawSize(int unit, float size) { 
        Context c = getContext(); 
        Resources r; 
 
        if (c == null) 
            r = Resources.getSystem(); 
        else 
            r = c.getResources(); 
         
        return TypedValue.applyDimension(unit, size, r.getDisplayMetrics()); 
    } 

摘自 android小益的專欄

發佈留言