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);
}
}