1. 程式人生 > >android TextView 分散對齊(兩端對齊)

android TextView 分散對齊(兩端對齊)



import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 對齊的TextView
 * <p>
 * 為了能夠使TextView能夠很好的進行排版,同時考慮到原生TextView中以word進行分割排版,
 * 那麼我們可以將要換行的地方進行新增空格處理,這樣就可以在合適的位置換行,同時也不會
 * 打亂原生的TextView的排版換行選擇複製等問題。為了能夠使右端儘可能的對齊,將右側多出的空隙
 * 儘可能的分配到該行的標點後面。達到兩段對齊的效果。
 * </p>
 * <p>
 * 重新設定文字前,請呼叫reset()進行狀態重置。
 * </p>
 * Created by Rivers on 6/28/18.
 */
public class AlignTextView extends TextView {
    private final static String TAG = AlignTextView.class.getSimpleName();
    private final static char SPACE = ' '; //空格;
    private List<Integer> addCharPosition = new ArrayList<Integer>();  //增加空格的位置
    private static List<Character> punctuation = new ArrayList<Character>(); //標點符號
    private CharSequence oldText = ""; //舊文字,本來應該顯示的文字
    private CharSequence newText = ""; //新文字,真正顯示的文字
    private boolean inProcess = false; //舊文字是否已經處理為新文字
    private boolean isAddPadding = false; //是否新增過邊距
    private boolean isConvert = false; //是否轉換標點符號

    //標點符號用於在textview右側多出空間時,將空間加到標點符號的後面,以便於右端對齊
    static {
        punctuation.clear();
        punctuation.add(',');
        punctuation.add('.');
        punctuation.add('?');
        punctuation.add('!');
        punctuation.add(';');
        punctuation.add(',');
        punctuation.add('。');
        punctuation.add('?');
        punctuation.add('!');
        punctuation.add(';');
        punctuation.add(')');
        punctuation.add('】');
        punctuation.add(')');
        punctuation.add(']');
        punctuation.add('}');
    }

    public AlignTextView(Context context) {
        super(context);
    }

    public AlignTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.AlignTextView);
        isConvert = ta.getBoolean(R.styleable.AlignTextView_punctuationConvert, false);
        ta.recycle();

        //判斷使用xml中是用android:text
        TypedArray tsa = context.obtainStyledAttributes(attrs, new int[]{
                android.R.attr.text
        });
        String text = tsa.getString(0);
        tsa.recycle();
        if (!TextUtils.isEmpty(text)) {
            setText(text);
        }
    }

    /**
     * 監聽文字複製,對於複製的文字進行空格剔除
     *
     * @param id 操作id(複製,全部選擇等)
     * @return 是否操作成功
     */
    @Override
    public boolean onTextContextMenuItem(int id) {
        if (id == android.R.id.copy) {

            if (isFocused()) {
                final int selStart = getSelectionStart();
                final int selEnd = getSelectionEnd();

                int min = Math.max(0, Math.min(selStart, selEnd));
                int max = Math.max(0, Math.max(selStart, selEnd));

                //利用反射獲取選擇的文字資訊,同時關閉操作框
                try {
                    Class cls = getClass().getSuperclass();
                    Method getSelectTextMethod = cls.getDeclaredMethod("getTransformedText", new
                            Class[]{int.class, int.class});
                    getSelectTextMethod.setAccessible(true);
                    CharSequence selectedText = (CharSequence) getSelectTextMethod.invoke(this,
                            min, max);
                    copy(selectedText.toString());

                    Method closeMenuMethod;
                    if (Build.VERSION.SDK_INT < 23) {
                        closeMenuMethod = cls.getDeclaredMethod("stopSelectionActionMode");
                    } else {
                        closeMenuMethod = cls.getDeclaredMethod("stopTextActionMode");
                    }
                    closeMenuMethod.setAccessible(true);
                    closeMenuMethod.invoke(this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return true;
        } else {
            return super.onTextContextMenuItem(id);
        }
    }


    /**
     * 複製文字到剪下板,去除新增字元
     *
     * @param text 文字
     */
    private void copy(String text) {
        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context
                .CLIPBOARD_SERVICE);
        int start = newText.toString().indexOf(text);
        int end = start + text.length();
        StringBuilder sb = new StringBuilder(text);
        for (int i = addCharPosition.size() - 1; i >= 0; i--) {
            int position = addCharPosition.get(i);
            if (position < end && position >= start) {
                sb.deleteCharAt(position - start);
            }
        }
        try {
            android.content.ClipData clip = android.content.ClipData.newPlainText(null, sb.toString());
            clipboard.setPrimaryClip(clip);
        }catch (Exception e){
           Log.e(TAG, e.getMessage());
        }
    }

    /**
     * 重置狀態
     */
    public void reset(){
        inProcess = false;
        addCharPosition.clear();
        newText = "";
        newText = "";
    }

    /**
     * 處理多行文字
     *
     * @param paint 畫筆
     * @param text  文字
     * @param width 最大可用寬度
     * @return 處理後的文字
     */
    private String processText(Paint paint, String text, int width) {
        if (text == null || text.length() == 0) {
            return "";
        }
        String[] lines = text.split("\\n");
        StringBuilder newText = new StringBuilder();
        for (String line : lines) {
            newText.append('\n');
            newText.append(processLine(paint, line, width, newText.length() - 1));
        }
        if (newText.length() > 0) {
            newText.deleteCharAt(0);
        }
        return newText.toString();
    }


    /**
     * 處理單行文字
     *
     * @param paint                     畫筆
     * @param text                      文字
     * @param width                     最大可用寬度
     * @param addCharacterStartPosition 新增文字的起始位置
     * @return 處理後的文字
     */
    private String processLine(Paint paint, String text, int width, int addCharacterStartPosition) {
        if (text == null || text.length() == 0) {
            return "";
        }

        StringBuilder old = new StringBuilder(text);
        int startPosition = 0; // 起始位置

        float chineseWidth = paint.measureText("中");
        float spaceWidth = paint.measureText(SPACE + "");

        //最大可容納的漢字,每一次從此位置向後推進計算
        int maxChineseCount = (int) (width / chineseWidth);

        //減少一個漢字寬度,保證每一行前後都有一個空格
        maxChineseCount--;

        //如果不能容納漢字,直接返回空串
        if (maxChineseCount <= 0) {
            return "";
        }

        for (int i = maxChineseCount; i < old.length(); i++) {
            if (paint.measureText(old.substring(startPosition, i + 1)) > (width - spaceWidth)) {

                //右側多餘空隙寬度
                float gap = (width - spaceWidth - paint.measureText(old.substring(startPosition,
                        i)));

                List<Integer> positions = new ArrayList<Integer>();
                for (int j = startPosition; j < i; j++) {
                    char ch = old.charAt(j);
                    if (punctuation.contains(ch)) {
                        positions.add(j + 1);
                    }
                }

                //空隙最多可以使用幾個空格替換
                int number = (int) (gap / spaceWidth);

                //多增加的空格數量
                int use = 0;

                if (positions.size() > 0) {
                    for (int k = 0; k < positions.size() && number > 0; k++) {
                        int times = number / (positions.size() - k);
                        int position = positions.get(k / positions.size());
                        for (int m = 0; m < times; m++) {
                            old.insert(position + m, SPACE);
                            addCharPosition.add(position + m + addCharacterStartPosition);
                            use++;
                            number--;
                        }
                    }
                }

                //指標移動,將段尾新增空格進行分行處理
                i = i + use;
                old.insert(i, SPACE);
                addCharPosition.add(i + addCharacterStartPosition);

                startPosition = i + 1;
                i = i + maxChineseCount;
            }
        }

        return old.toString();
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        //父類初始化的時候子類暫時沒有初始化, 覆蓋方法會被執行,遮蔽掉
        if (addCharPosition == null) {
            super.setText(text, type);
            return;
        }
        if (!inProcess && (text != null && !text.equals(newText))) {
            oldText = text;
            process(false);
            super.setText(newText, type);
        } else {
            //恢復初始狀態
            inProcess = false;
            super.setText(text, type);
        }
    }

    /**
     * 獲取真正的text
     *
     * @return 返回text
     */
    public CharSequence getRealText() {
        return oldText;
    }

    /**
     * 文字轉化
     *
     * @param setText 是否設定textView的文字
     */
    private void process(boolean setText) {
        if (oldText == null) {
            oldText = "";
        }
        if (!inProcess && getVisibility() == VISIBLE) {
            addCharPosition.clear();

            //轉化字元,5.0系統對字型處理有所變動
            if (isConvert) {
                oldText = AlignTextViewUtil.replacePunctuation(oldText.toString());
            }

            if (getWidth() == 0) {
                //沒有測量完畢,等待測量完畢後處理
                post(new Runnable() {
                    @Override
                    public void run() {
                        process(true);
                    }
                });
                return;
            }

            //新增過邊距之後不再次新增
            if (!isAddPadding) {
                int spaceWidth = (int) (getPaint().measureText(SPACE + ""));
                newText = processText(getPaint(), oldText.toString(), getWidth() - getPaddingLeft
                        () -
                        getPaddingRight() - spaceWidth);
                setPadding(getPaddingLeft() + spaceWidth, getPaddingTop(), getPaddingRight(),
                        getPaddingBottom());
                isAddPadding = true;
            } else {
                newText = processText(getPaint(), oldText.toString(), getWidth() - getPaddingLeft
                        () -
                        getPaddingRight());
            }
            inProcess = true;
            if (setText) {
                setText(newText);
            }
        }
    }

    /**
     * 是否轉化標點符號,將中文標點轉化為英文標點
     *
     * @param convert 是否轉化
     */
    public void setPunctuationConvert(boolean convert) {
        isConvert = convert;
    }
}
/**
 * 文字工具
 */
public class AlignTextViewUtil {

    /**
     * 將中文標點替換為英文標點
     *
     * @param text 要替換的文字
     * @return 替換後的文字
     */
    public static String replacePunctuation(String text) {
        text = text.replace(',', ',').replace('。', '.').replace('【', '[').replace('】', ']')
                .replace('?', '?').replace('!', '!').replace('(', '(').replace(')', ')').replace
                        ('“', '"').replace('”', '"');
        return text;
    }
}

res/values/aligntextview_attr.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- 末行對齊方式 -->
    <declare-styleable name="AlignTextView">
        <attr name="align" format="enum">
            <enum name="left" value="0"/>
            <enum name="center" value="1"/>
            <enum name="right" value="2"/>
        </attr>
    </declare-styleable>

    <!-- 標點轉換 -->
    <declare-styleable name="CBAlignTextView">
        <attr name="punctuationConvert" format="boolean"/>
    </declare-styleable>


</resources>

如果需要支援android預設的選擇複製,請在xml中加入以下程式碼:

android:textIsSelectable="true"