TextView英文自動換行解決方法
阿新 • • 發佈:2019-01-10
TextView元件
遇到一個問題:
想將【TP-LINK_XXXXXXX】已ellipsize="end'的方式展示一部分,設定
android:layout_width="400px"
android:ellipsize="end"
android:maxLines="1"
android:lines="1"
以為顯示的結果為:TP-LINK…
結果:TP-…
查了大堆資料,有人說是android原始碼的缺陷,總結了以下解決方法:
1、將半形轉全形(太難看了,難以接受)
2、重寫TextView(這個方法確實能解決問題,大神確實多)
3、強大的TextJustify控制元件(搬運,自測有點卡,小工程不用考慮使用):https://github.com/GitHubSMXY/TextJustify-Android
詳情,轉載自:
http://www.cnblogs.com/goagent/p/5159125.html
玩法原始碼(新增了方法):
public class XRTextView extends TextView { private boolean mEnabled = true; public XRTextView(Context context) { super(context); } public XRTextView(Context context, AttributeSet attrs) { super(context,attrs); } public XRTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setAutoSplitEnabled(boolean enabled) { mEnabled = enabled; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if(MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY && getWidth() > 0 && getHeight() > 0 && mEnabled) { String newText = autoSplitText(this); if (!TextUtils.isEmpty(newText)) { setText(newText); } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } private String autoSplitText(final TextView tv) { final String rawText = tv.getText().toString(); //原始文字 final Paint tvPaint = tv.getPaint(); //paint,包含字型等資訊 final float tvWidth = tv.getWidth() - tv.getPaddingLeft() - tv.getPaddingRight(); //控制元件可用寬度 //將原始文字按行拆分 String[] rawTextLines = rawText.replaceAll("\r", "").split("\n"); StringBuilder sbNewText = new StringBuilder(); for (String rawTextLine : rawTextLines) { if (tvPaint.measureText(rawTextLine) <= tvWidth) { //如果整行寬度在控制元件可用寬度之內,就不處理了 sbNewText.append(rawTextLine); } else { //如果整行寬度超過控制元件可用寬度,則按字元測量,在超過可用寬度的前一個字元處手動換行 float lineWidth = 0; for (int cnt = 0; cnt != rawTextLine.length(); ++cnt) { char ch = rawTextLine.charAt(cnt); lineWidth += tvPaint.measureText(String.valueOf(ch)); if (lineWidth <= tvWidth) { sbNewText.append(ch); } else { sbNewText.append("\n"); lineWidth = 0; --cnt; } } } sbNewText.append("\n"); } //把結尾多餘的\n去掉 if (!rawText.endsWith("\n")) { sbNewText.deleteCharAt(sbNewText.length() - 1); } return sbNewText.toString(); } public void setFont(String textFont) { Typeface lastTypeFace = getTypeface(); boolean isBold = lastTypeFace != null ? lastTypeFace.isBold() : false; Typeface typeface = FontUtil.getTypeface(textFont, getContext()); //使用字型 setTypeface(typeface); //中文字型設定加粗 TextPaint paint = getPaint(); paint.setFakeBoldText(isBold); } }