(); // 尾行
26 | private Align align = Align.ALIGN_LEFT; // 默认最后一行左对齐
27 | private boolean firstCalc = true; // 初始化计算
28 |
29 | private float lineSpacingMultiplier = 1.0f;
30 | private float lineSpacingAdd = 0.0f;
31 |
32 | private int originalHeight = 0; //原始高度
33 | private int originalLineCount = 0; //原始行数
34 | private int originalPaddingBottom = 0; //原始paddingBottom
35 | private boolean setPaddingFromMe = false;
36 |
37 | // 尾行对齐方式
38 | public enum Align {
39 | ALIGN_LEFT, ALIGN_CENTER, ALIGN_RIGHT // 居中,居左,居右,针对段落最后一行
40 | }
41 |
42 | public AlignTextView(Context context) {
43 | super(context);
44 | setTextIsSelectable(false);
45 | }
46 |
47 | public AlignTextView(Context context, AttributeSet attrs) {
48 | super(context, attrs);
49 | setTextIsSelectable(false);
50 |
51 | int[] attributes = new int[]{android.R.attr.lineSpacingExtra, android.R.attr.lineSpacingMultiplier};
52 | TypedArray arr = context.obtainStyledAttributes(attrs, attributes);
53 | lineSpacingAdd = arr.getDimensionPixelSize(0, 0);
54 | lineSpacingMultiplier = arr.getFloat(1, 1.0f);
55 | originalPaddingBottom = getPaddingBottom();
56 | arr.recycle();
57 |
58 | TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.AlignTextView);
59 |
60 | int alignStyle = ta.getInt(R.styleable.AlignTextView_align, 0);
61 | switch (alignStyle) {
62 | case 1:
63 | align = Align.ALIGN_CENTER;
64 | break;
65 | case 2:
66 | align = Align.ALIGN_RIGHT;
67 | break;
68 | default:
69 | align = Align.ALIGN_LEFT;
70 | break;
71 | }
72 |
73 | ta.recycle();
74 | }
75 |
76 |
77 | @Override
78 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
79 | super.onLayout(changed, left, top, right, bottom);
80 |
81 | //首先进行高度调整
82 | if (firstCalc) {
83 | width = getMeasuredWidth();
84 | String text = getText().toString();
85 | TextPaint paint = getPaint();
86 | lines.clear();
87 | tailLines.clear();
88 |
89 | // 文本含有换行符时,分割单独处理
90 | String[] items = text.split("\\n");
91 | for (String item : items) {
92 | calc(paint, item);
93 | }
94 |
95 | //使用替代textview计算原始高度与行数
96 | measureTextViewHeight(text, paint.getTextSize(), getMeasuredWidth() -
97 | getPaddingLeft() - getPaddingRight());
98 |
99 | //获取行高
100 | textHeight = 1.0f * originalHeight / originalLineCount;
101 |
102 | textLineSpaceExtra = textHeight * (lineSpacingMultiplier - 1) + lineSpacingAdd;
103 |
104 | //计算实际高度,加上多出的行的高度(一般是减少)
105 | int heightGap = (int) ((textLineSpaceExtra + textHeight) * (lines.size() -
106 | originalLineCount));
107 |
108 | setPaddingFromMe = true;
109 | //调整textview的paddingBottom来缩小底部空白
110 | setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(),
111 | originalPaddingBottom + heightGap);
112 |
113 | firstCalc = false;
114 | }
115 | }
116 |
117 | @Override
118 | protected void onDraw(Canvas canvas) {
119 | TextPaint paint = getPaint();
120 | paint.setColor(getCurrentTextColor());
121 | paint.drawableState = getDrawableState();
122 |
123 | width = getMeasuredWidth();
124 |
125 | Paint.FontMetrics fm = paint.getFontMetrics();
126 | float firstHeight = getTextSize() - (fm.bottom - fm.descent + fm.ascent - fm.top);
127 |
128 | int gravity = getGravity();
129 | if ((gravity & 0x1000) == 0) { // 是否垂直居中
130 | firstHeight = firstHeight + (textHeight - firstHeight) / 2;
131 | }
132 |
133 | int paddingTop = getPaddingTop();
134 | int paddingLeft = getPaddingLeft();
135 | int paddingRight = getPaddingRight();
136 | width = width - paddingLeft - paddingRight;
137 |
138 | for (int i = 0; i < lines.size(); i++) {
139 | float drawY = i * textHeight + firstHeight;
140 | String line = lines.get(i);
141 | // 绘画起始x坐标
142 | float drawSpacingX = paddingLeft;
143 | float gap = (width - paint.measureText(line));
144 | float interval = gap / (line.length() - 1);
145 |
146 | // 绘制最后一行
147 | if (tailLines.contains(i)) {
148 | interval = 0;
149 | if (align == Align.ALIGN_CENTER) {
150 | drawSpacingX += gap / 2;
151 | } else if (align == Align.ALIGN_RIGHT) {
152 | drawSpacingX += gap;
153 | }
154 | }
155 |
156 | for (int j = 0; j < line.length(); j++) {
157 | float drawX = paint.measureText(line.substring(0, j)) + interval * j;
158 | canvas.drawText(line.substring(j, j + 1), drawX + drawSpacingX, drawY +
159 | paddingTop + textLineSpaceExtra * i, paint);
160 | }
161 | }
162 | }
163 |
164 | /**
165 | * 设置尾行对齐方式
166 | *
167 | * @param align 对齐方式
168 | */
169 | public void setAlign(Align align) {
170 | this.align = align;
171 | invalidate();
172 | }
173 |
174 | /**
175 | * 计算每行应显示的文本数
176 | *
177 | * @param text 要计算的文本
178 | */
179 | private void calc(Paint paint, String text) {
180 | if (text.length() == 0) {
181 | lines.add("\n");
182 | return;
183 | }
184 | int startPosition = 0; // 起始位置
185 | float oneChineseWidth = paint.measureText("中");
186 | int ignoreCalcLength = (int) (width / oneChineseWidth); // 忽略计算的长度
187 | StringBuilder sb = new StringBuilder(text.substring(0, Math.min(ignoreCalcLength + 1,
188 | text.length())));
189 |
190 | for (int i = ignoreCalcLength + 1; i < text.length(); i++) {
191 | if (paint.measureText(text.substring(startPosition, i + 1)) > width) {
192 | startPosition = i;
193 | //将之前的字符串加入列表中
194 | lines.add(sb.toString());
195 |
196 | sb = new StringBuilder();
197 |
198 | //添加开始忽略的字符串,长度不足的话直接结束,否则继续
199 | if ((text.length() - startPosition) > ignoreCalcLength) {
200 | sb.append(text.substring(startPosition, startPosition + ignoreCalcLength));
201 | } else {
202 | lines.add(text.substring(startPosition));
203 | break;
204 | }
205 |
206 | i = i + ignoreCalcLength - 1;
207 | } else {
208 | sb.append(text.charAt(i));
209 | }
210 | }
211 | if (sb.length() > 0) {
212 | lines.add(sb.toString());
213 | }
214 |
215 | tailLines.add(lines.size() - 1);
216 | }
217 |
218 |
219 | @Override
220 | public void setText(CharSequence text, BufferType type) {
221 | firstCalc = true;
222 | super.setText(text, type);
223 | }
224 |
225 | @Override
226 | public void setPadding(int left, int top, int right, int bottom) {
227 | if (!setPaddingFromMe) {
228 | originalPaddingBottom = bottom;
229 | }
230 | setPaddingFromMe = false;
231 | super.setPadding(left, top, right, bottom);
232 | }
233 |
234 |
235 | /**
236 | * 获取文本实际所占高度,辅助用于计算行高,行数
237 | *
238 | * @param text 文本
239 | * @param textSize 字体大小
240 | * @param deviceWidth 屏幕宽度
241 | */
242 | private void measureTextViewHeight(String text, float textSize, int deviceWidth) {
243 | TextView textView = new TextView(getContext());
244 | textView.setText(text);
245 | textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
246 | int widthMeasureSpec = MeasureSpec.makeMeasureSpec(deviceWidth, MeasureSpec.EXACTLY);
247 | int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
248 | textView.measure(widthMeasureSpec, heightMeasureSpec);
249 | originalLineCount = textView.getLineCount();
250 | originalHeight = textView.getMeasuredHeight();
251 | }
252 | }
--------------------------------------------------------------------------------
/align-text-view-example/align-text-view-example.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 | generateDebugSources
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/align-text-view/src/main/java/me/codeboy/android/aligntextview/CBAlignTextView.java:
--------------------------------------------------------------------------------
1 | package me.codeboy.android.aligntextview;
2 |
3 | import android.content.ClipboardManager;
4 | import android.content.Context;
5 | import android.content.res.TypedArray;
6 | import android.graphics.Paint;
7 | import android.os.Build;
8 | import android.text.TextUtils;
9 | import android.util.AttributeSet;
10 | import android.util.Log;
11 | import android.widget.TextView;
12 |
13 | import java.lang.reflect.Method;
14 | import java.util.ArrayList;
15 | import java.util.List;
16 |
17 | import me.codeboy.android.aligntextview.util.CBAlignTextViewUtil;
18 |
19 | /**
20 | * 对齐的TextView
21 | *
22 | * 为了能够使TextView能够很好的进行排版,同时考虑到原生TextView中以word进行分割排版,
23 | * 那么我们可以将要换行的地方进行添加空格处理,这样就可以在合适的位置换行,同时也不会
24 | * 打乱原生的TextView的排版换行选择复制等问题。为了能够使右端尽可能的对齐,将右侧多出的空隙
25 | * 尽可能的分配到该行的标点后面。达到两段对齐的效果。
26 | *
27 | *
28 | * 重新设置文本前,请调用reset()进行状态重置。
29 | *
30 | * Created by yuedong.lyd on 6/28/15.
31 | */
32 | public class CBAlignTextView extends TextView {
33 | private final static String TAG = CBAlignTextView.class.getSimpleName();
34 | private final static char SPACE = ' '; //空格;
35 | private List addCharPosition = new ArrayList(); //增加空格的位置
36 | private static List punctuation = new ArrayList(); //标点符号
37 | private CharSequence oldText = ""; //旧文本,本来应该显示的文本
38 | private CharSequence newText = ""; //新文本,真正显示的文本
39 | private boolean inProcess = false; //旧文本是否已经处理为新文本
40 | private boolean isAddPadding = false; //是否添加过边距
41 | private boolean isConvert = false; //是否转换标点符号
42 |
43 | //标点符号用于在textview右侧多出空间时,将空间加到标点符号的后面,以便于右端对齐
44 | static {
45 | punctuation.clear();
46 | punctuation.add(',');
47 | punctuation.add('.');
48 | punctuation.add('?');
49 | punctuation.add('!');
50 | punctuation.add(';');
51 | punctuation.add(',');
52 | punctuation.add('。');
53 | punctuation.add('?');
54 | punctuation.add('!');
55 | punctuation.add(';');
56 | punctuation.add(')');
57 | punctuation.add('】');
58 | punctuation.add(')');
59 | punctuation.add(']');
60 | punctuation.add('}');
61 | }
62 |
63 | public CBAlignTextView(Context context) {
64 | super(context);
65 | }
66 |
67 | public CBAlignTextView(Context context, AttributeSet attrs) {
68 | super(context, attrs);
69 | TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CBAlignTextView);
70 | isConvert = ta.getBoolean(R.styleable.CBAlignTextView_punctuationConvert, false);
71 | ta.recycle();
72 |
73 | //判断使用xml中是用android:text
74 | TypedArray tsa = context.obtainStyledAttributes(attrs, new int[]{
75 | android.R.attr.text
76 | });
77 | String text = tsa.getString(0);
78 | tsa.recycle();
79 | if (!TextUtils.isEmpty(text)) {
80 | setText(text);
81 | }
82 | }
83 |
84 | /**
85 | * 监听文本复制,对于复制的文本进行空格剔除
86 | *
87 | * @param id 操作id(复制,全部选择等)
88 | * @return 是否操作成功
89 | */
90 | @Override
91 | public boolean onTextContextMenuItem(int id) {
92 | if (id == android.R.id.copy) {
93 |
94 | if (isFocused()) {
95 | final int selStart = getSelectionStart();
96 | final int selEnd = getSelectionEnd();
97 |
98 | int min = Math.max(0, Math.min(selStart, selEnd));
99 | int max = Math.max(0, Math.max(selStart, selEnd));
100 |
101 | //利用反射获取选择的文本信息,同时关闭操作框
102 | try {
103 | Class cls = getClass().getSuperclass();
104 | Method getSelectTextMethod = cls.getDeclaredMethod("getTransformedText", new
105 | Class[]{int.class, int.class});
106 | getSelectTextMethod.setAccessible(true);
107 | CharSequence selectedText = (CharSequence) getSelectTextMethod.invoke(this,
108 | min, max);
109 | copy(selectedText.toString());
110 |
111 | Method closeMenuMethod;
112 | if (Build.VERSION.SDK_INT < 23) {
113 | closeMenuMethod = cls.getDeclaredMethod("stopSelectionActionMode");
114 | } else {
115 | closeMenuMethod = cls.getDeclaredMethod("stopTextActionMode");
116 | }
117 | closeMenuMethod.setAccessible(true);
118 | closeMenuMethod.invoke(this);
119 | } catch (Exception e) {
120 | e.printStackTrace();
121 | }
122 | }
123 | return true;
124 | } else {
125 | return super.onTextContextMenuItem(id);
126 | }
127 | }
128 |
129 |
130 | /**
131 | * 复制文本到剪切板,去除添加字符
132 | *
133 | * @param text 文本
134 | */
135 | private void copy(String text) {
136 | ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context
137 | .CLIPBOARD_SERVICE);
138 | int start = newText.toString().indexOf(text);
139 | int end = start + text.length();
140 | StringBuilder sb = new StringBuilder(text);
141 | for (int i = addCharPosition.size() - 1; i >= 0; i--) {
142 | int position = addCharPosition.get(i);
143 | if (position < end && position >= start) {
144 | sb.deleteCharAt(position - start);
145 | }
146 | }
147 | try {
148 | android.content.ClipData clip = android.content.ClipData.newPlainText(null, sb.toString());
149 | clipboard.setPrimaryClip(clip);
150 | }catch (Exception e){
151 | Log.e(TAG, e.getMessage());
152 | }
153 | }
154 |
155 | /**
156 | * 重置状态
157 | */
158 | public void reset(){
159 | inProcess = false;
160 | addCharPosition.clear();
161 | newText = "";
162 | newText = "";
163 | }
164 |
165 | /**
166 | * 处理多行文本
167 | *
168 | * @param paint 画笔
169 | * @param text 文本
170 | * @param width 最大可用宽度
171 | * @return 处理后的文本
172 | */
173 | private String processText(Paint paint, String text, int width) {
174 | if (text == null || text.length() == 0) {
175 | return "";
176 | }
177 | String[] lines = text.split("\\n");
178 | StringBuilder newText = new StringBuilder();
179 | for (String line : lines) {
180 | newText.append('\n');
181 | newText.append(processLine(paint, line, width, newText.length() - 1));
182 | }
183 | if (newText.length() > 0) {
184 | newText.deleteCharAt(0);
185 | }
186 | return newText.toString();
187 | }
188 |
189 |
190 | /**
191 | * 处理单行文本
192 | *
193 | * @param paint 画笔
194 | * @param text 文本
195 | * @param width 最大可用宽度
196 | * @param addCharacterStartPosition 添加文本的起始位置
197 | * @return 处理后的文本
198 | */
199 | private String processLine(Paint paint, String text, int width, int addCharacterStartPosition) {
200 | if (text == null || text.length() == 0) {
201 | return "";
202 | }
203 |
204 | StringBuilder old = new StringBuilder(text);
205 | int startPosition = 0; // 起始位置
206 |
207 | float chineseWidth = paint.measureText("中");
208 | float spaceWidth = paint.measureText(SPACE + "");
209 |
210 | //最大可容纳的汉字,每一次从此位置向后推进计算
211 | int maxChineseCount = (int) (width / chineseWidth);
212 |
213 | //减少一个汉字宽度,保证每一行前后都有一个空格
214 | maxChineseCount--;
215 |
216 | //如果不能容纳汉字,直接返回空串
217 | if (maxChineseCount <= 0) {
218 | return "";
219 | }
220 |
221 | for (int i = maxChineseCount; i < old.length(); i++) {
222 | if (paint.measureText(old.substring(startPosition, i + 1)) > (width - spaceWidth)) {
223 |
224 | //右侧多余空隙宽度
225 | float gap = (width - spaceWidth - paint.measureText(old.substring(startPosition,
226 | i)));
227 |
228 | List positions = new ArrayList();
229 | for (int j = startPosition; j < i; j++) {
230 | char ch = old.charAt(j);
231 | if (punctuation.contains(ch)) {
232 | positions.add(j + 1);
233 | }
234 | }
235 |
236 | //空隙最多可以使用几个空格替换
237 | int number = (int) (gap / spaceWidth);
238 |
239 | //多增加的空格数量
240 | int use = 0;
241 |
242 | if (positions.size() > 0) {
243 | for (int k = 0; k < positions.size() && number > 0; k++) {
244 | int times = number / (positions.size() - k);
245 | int position = positions.get(k / positions.size());
246 | for (int m = 0; m < times; m++) {
247 | old.insert(position + m, SPACE);
248 | addCharPosition.add(position + m + addCharacterStartPosition);
249 | use++;
250 | number--;
251 | }
252 | }
253 | }
254 |
255 | //指针移动,将段尾添加空格进行分行处理
256 | i = i + use;
257 | old.insert(i, SPACE);
258 | addCharPosition.add(i + addCharacterStartPosition);
259 |
260 | startPosition = i + 1;
261 | i = i + maxChineseCount;
262 | }
263 | }
264 |
265 | return old.toString();
266 | }
267 |
268 | @Override
269 | public void setText(CharSequence text, BufferType type) {
270 | //父类初始化的时候子类暂时没有初始化, 覆盖方法会被执行,屏蔽掉
271 | if (addCharPosition == null) {
272 | super.setText(text, type);
273 | return;
274 | }
275 | if (!inProcess && (text != null && !text.equals(newText))) {
276 | oldText = text;
277 | process(false);
278 | super.setText(newText, type);
279 | } else {
280 | //恢复初始状态
281 | inProcess = false;
282 | super.setText(text, type);
283 | }
284 | }
285 |
286 | /**
287 | * 获取真正的text
288 | *
289 | * @return 返回text
290 | */
291 | public CharSequence getRealText() {
292 | return oldText;
293 | }
294 |
295 | /**
296 | * 文本转化
297 | *
298 | * @param setText 是否设置textView的文本
299 | */
300 | private void process(boolean setText) {
301 | if (oldText == null) {
302 | oldText = "";
303 | }
304 | if (!inProcess && getVisibility() == VISIBLE) {
305 | addCharPosition.clear();
306 |
307 | //转化字符,5.0系统对字体处理有所变动
308 | if (isConvert) {
309 | oldText = CBAlignTextViewUtil.replacePunctuation(oldText.toString());
310 | }
311 |
312 | if (getWidth() == 0) {
313 | //没有测量完毕,等待测量完毕后处理
314 | post(new Runnable() {
315 | @Override
316 | public void run() {
317 | process(true);
318 | }
319 | });
320 | return;
321 | }
322 |
323 | //添加过边距之后不再次添加
324 | if (!isAddPadding) {
325 | int spaceWidth = (int) (getPaint().measureText(SPACE + ""));
326 | newText = processText(getPaint(), oldText.toString(), getWidth() - getPaddingLeft
327 | () -
328 | getPaddingRight() - spaceWidth);
329 | setPadding(getPaddingLeft() + spaceWidth, getPaddingTop(), getPaddingRight(),
330 | getPaddingBottom());
331 | isAddPadding = true;
332 | } else {
333 | newText = processText(getPaint(), oldText.toString(), getWidth() - getPaddingLeft
334 | () -
335 | getPaddingRight());
336 | }
337 | inProcess = true;
338 | if (setText) {
339 | setText(newText);
340 | }
341 | }
342 | }
343 |
344 | /**
345 | * 是否转化标点符号,将中文标点转化为英文标点
346 | *
347 | * @param convert 是否转化
348 | */
349 | public void setPunctuationConvert(boolean convert) {
350 | isConvert = convert;
351 | }
352 | }
--------------------------------------------------------------------------------