解決部分場景TextView換行對齊

背景

原生textview換行會出現換行,右側文字參差不齊,最近公司產品經理看不下去了,要求盡可能要對齊,保持美觀。通過我花了一些時間來研究, 發現大部分原因是因為句子中含有中英文標點符號,可以通過替換中文標點符號解決,文字半角轉換為全角,對于一些頑固的情況, 通過繪制寬度來解決,最終達成自己要想的效果。

效果

原生換行:

yuansheng.png

自定義textview換行:

zidingyi.png
替換中文符號:
public String stringFilter(String str) {
        str = str.replaceAll("【", "[").replaceAll("】", "]").replaceAll("!", "!").replaceAll(":", ":");// 替換中文標號
        String regEx = "[『』]"; // 清除掉特殊字符
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }
半角轉換為全角:
public String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {// 全角空格為12288,半角空格為32
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)// 其他字符半角(33-126)與全角(65281-65374)的對應關系是:均相差65248
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

測試代碼

1.布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.lenovo.mytest1708.SecondActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:maxWidth="200dp"
        android:text="原生textview"
        android:visibility="gone"
        android:layout_centerInParent="true"
        android:layout_height="wrap_content"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:orientation="vertical"
        android:visibility="visible"
        android:layout_centerInParent="true"
        android:layout_height="wrap_content">

        <View
            android:layout_width="match_parent"
            android:background="#beecd3"
            android:layout_height="20dp"/>

        <com.example.lenovo.mytest1708.view.CustomAlignTextView
            android:id="@+id/text001"
            android:maxWidth="200dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="自定義textview"
            android:background="#beecd3"
            android:visibility="visible"/>

        <View
            android:layout_width="match_parent"
            android:background="#beecd3"
            android:layout_height="20dp"/>

    </LinearLayout>

</RelativeLayout>

2.自定義textview:

package com.example.lenovo.mytest1708.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import android.view.View;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by blueocean on 2017/8/23.
 * desc: 自定義換行對齊textview
 */

public class CustomAlignTextView extends AppCompatTextView {

    private final String namespace = "rong.android.TextView";
    private String text;
    private float textSize;
    private int paddingLeft;
    private int paddingRight;
    private int paddingTop;
    private int paddingBottom;
    private float marginLeft;
    private float marginTop;
    private float marginRight;
    private float marginBottom;
    private int textColor;
    private JSONArray colorIndex;
    private Paint paint1 = new Paint();
    private Paint paintColor = new Paint();
    private float textShowWidth;
    private float Spacing = 0;
    private float LineSpacing = 1.3f;//行與行的間距

    public CustomAlignTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        text = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "text");
        textSize = attrs.getAttributeIntValue(namespace, "textSize", 25);//字體大小
        textColor = attrs.getAttributeIntValue(namespace, "textColor", Color.BLACK);//字體顏色
        paddingLeft = attrs.getAttributeIntValue(namespace, "paddingLeft", 0);
        paddingRight = attrs.getAttributeIntValue(namespace, "paddingRight", 0);
        paddingTop = attrs.getAttributeIntValue(namespace, "paddingTop", 0);
        paddingBottom = attrs.getAttributeIntValue(namespace, "paddingBottom", 0);
        marginLeft = attrs.getAttributeIntValue(namespace, "marginLeft", 0);
        marginRight = attrs.getAttributeIntValue(namespace, "marginRight", 0);
        marginTop = attrs.getAttributeIntValue(namespace, "marginTop", 0);
        marginBottom = attrs.getAttributeIntValue(namespace, "marginBottom", 0);
        paint1.setTextSize(textSize);
        paint1.setColor(textColor);
        paint1.setAntiAlias(true);
        paintColor.setAntiAlias(true);
        paintColor.setTextSize(textSize);
        paintColor.setColor(Color.BLACK);
    }

    public CustomAlignTextView(Context context, float textSize, int textColor, int paddingLeft, int paddingRight, float marginLeft, float marginRight) {
        super(context);
        this.textSize = textSize;
        this.textColor = textColor;
        this.paddingLeft = paddingLeft;
        this.paddingRight = paddingRight;
        this.marginLeft = marginLeft;
        this.marginRight = marginRight;
        paint1.setTextSize(textSize);
        paint1.setColor(textColor);
        paint1.setAntiAlias(true);
        paintColor.setAntiAlias(true);
        paintColor.setTextSize(textSize);
        paintColor.setColor(Color.BLACK);
    }


    public JSONArray getColorIndex() {
        return colorIndex;
    }

    public void setColorIndex(JSONArray colorIndex) {
        this.colorIndex = colorIndex;
    }

    /**
     * 傳入一個索引,判斷當前字是否被高亮
     *
     * @param index
     * @return
     * @throws JSONException
     */
    public boolean isColor(int index) throws JSONException {
        if (colorIndex == null) {
            return false;
        }
        for (int i = 0; i < colorIndex.length(); i++) {
            JSONArray array = colorIndex.getJSONArray(i);
            int start = array.getInt(0);
            int end = array.getInt(1) - 1;
            if (index >= start && index <= end) {
                return true;
            }
        }
        return false;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        //      super.onDraw(canvas);
        View view = (View) this.getParent();
        textShowWidth = view.getMeasuredWidth() - paddingLeft - paddingRight - marginLeft - marginRight;
        int lineCount = 0;

        text = this.getText().toString();//.replaceAll("\n", "\r\n");
        char[] textCharArray = text.toCharArray();
        // 已繪的寬度
        float drawedWidth = 0;
        float charWidth;
        for (int i = 0; i < textCharArray.length; i++) {
            charWidth = paint1.measureText(textCharArray, i, 1);

            if (textCharArray[i] == '\n') {
                lineCount++;
                drawedWidth = 0;
                continue;
            }
            if (textShowWidth - drawedWidth < charWidth) {
                lineCount++;
                drawedWidth = 0;
            }
            boolean color = false;
            try {
                color = isColor(i);
            } catch (JSONException e1) {
                e1.printStackTrace();
            }

            if (color) {

                canvas.drawText(textCharArray, i, 1, paddingLeft + drawedWidth, (lineCount + 1) * textSize * LineSpacing, paintColor);
            } else {

                canvas.drawText(textCharArray, i, 1, paddingLeft + drawedWidth, (lineCount + 1) * textSize * LineSpacing, paint1);
            }

            if (textCharArray[i] > 127 && textCharArray[i] != '、' && textCharArray[i] != ',' && textCharArray[i] != '。' && textCharArray[i] != ':' && textCharArray[i] != '!') {

                drawedWidth += charWidth + Spacing;

            } else {
                drawedWidth += charWidth;

            }
        }
        setHeight((int) ((lineCount + 1) * (int) textSize * LineSpacing + 10));
    }

    public void setAlignTextColor(int colorVal) {
        textColor = colorVal;
        paint1.setColor(textColor);
        paintColor.setColor(textColor);

        super.setTextColor(textColor);
    }

    public void setAlignPadding(int left, int right, int top, int bottom) {

        paddingLeft = left;
        paddingRight = right;
        paddingTop = top;
        paddingBottom = bottom;

        super.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
    }

    public void setAlignMargin(float left, float right, float top, float bottom) {

        marginLeft = left;
        marginRight = right;
        marginTop = top;
        marginBottom = bottom;

    }

    public void setAlignSpacing(float spacing) {
        Spacing = spacing;
    }

    public void setAlignLineSpacing(float lineSpacing) {
        LineSpacing = lineSpacing;
    }

    public void setAlignTextSize(float textSize) {
        this.textSize = textSize;
        paint1.setTextSize(textSize);
        paintColor.setTextSize(textSize);
        super.setTextSize(textSize);
    }

    public void setText(String text) {
        this.text = stringFilter(ToDBC(text));
        super.setText(this.text);
    }

    /**
     * 半角轉換為全角
     *
     * @param input
     * @return
     */
    public String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {// 全角空格為12288,半角空格為32
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)// 其他字符半角(33-126)與全角(65281-65374)的對應關系是:均相差65248
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    /**
     * 去除特殊字符或將所有中文標號替換為英文標號
     *
     * @param str
     * @return
     */
    public String stringFilter(String str) {
        str = str.replaceAll("【", "[").replaceAll("】", "]").replaceAll("!", "!").replaceAll(":", ":");// 替換中文標號
        String regEx = "[『』]"; // 清除掉特殊字符
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }
}

3.主activity:

package com.example.lenovo.mytest1708;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.example.lenovo.mytest1708.view.CustomAlignTextView;

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        TextView tv = (TextView) findViewById(R.id.text);
        CustomAlignTextView text = (CustomAlignTextView) findViewById(R.id.text001);

        String str = "恭喜您成功邀請到測試一森(4544587979182)加入海洋大家庭,快帶小伙伴開啟創業之旅吧!恭喜您成功邀請到測試一森(4544587979182)加入海洋大家庭,快帶小伙伴開啟創業之旅吧!恭喜您成功邀請到測試一森(4544587979182)加入海洋大家庭,快帶小伙伴開啟創業之旅吧!";

        text.setAlignTextColor(getResources().getColor(R.color.colorAccent));
        text.setAlignTextSize(sp2px(this, 15));
        //top,buttom暫時無效, 可通過view或space來設置,歡迎高手來指導
        text.setAlignPadding(dip2px(this, 20), dip2px(this, 20), 0, 0);

        tv.setText(str);
        text.setText(str);

    }

    /**
     * 將sp值轉換為px值,保證文字大小不變
     *
     * @param spValue
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 將px值轉換為sp值,保證文字大小不變
     *
     * @param pxValue
     * @return
     */

    public int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 根據手機的分辨率從 dp 的單位 轉成為 px(像素)
     */
    public int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根據手機的分辨率從 px(像素) 的單位 轉成為 dp
     */
    public int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}

可能達不到某些場景的理想效果, 但是有借鑒的地方, 還請各位大神多多賜教...

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,501評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,673評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,610評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,939評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,668評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,004評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,001評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,173評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,705評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,426評論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,656評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,139評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,833評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,247評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,580評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,371評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,621評論 2 380

推薦閱讀更多精彩內容