1. 程式人生 > >TextView自定義省略號、部分文字變色、部分文字點選

TextView自定義省略號、部分文字變色、部分文字點選

1、如果文字內容超過最大行數,在兩個字串拼接處新增省略號省略程式碼:

ViewTreeObserver observer = textView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

@Override
public void onGlobalLayout() {
ViewTreeObserver obs = textView.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this
);
if (textView.getLineCount() > maxLine) {//判斷行數大於多少時改變
int lineEndIndex = textView.getLayout().getLineEnd(maxLine - 1); //設定第maxLine行打省略號
String subStr = str.substring(str.lastIndexOf(strFlag));
Log.i("subStr", subStr);
String text = textView.getText().subSequence(0, lineEndIndex - subStr.length()) + "..."
+ subStr;
textView.setText(text);
}
}
});
}

2、部分文字變顏色:

String str = "小明回覆小紅:";
int firstStartIndex = 0;
int firstBendIndex = str.indexOf("回覆");
int secondStartIndex = str.indexOf("回覆") + "回覆".length();
int secondBendIndex = str.indexOf(":");
SpannableStringBuilder style = new SpannableStringBuilder(str);
style.setSpan(new BackgroundColorSpan(Color.BLACK), firstStartIndex, firstBendIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
style.setSpan(new ForegroundColorSpan(Color.BLUE), firstStartIndex, firstBendIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
style.setSpan(new ForegroundColorSpan(Color.RED), secondStartIndex, secondBendIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
text_view.setText(style);

3、部分文字可點選:

String str = "小明回覆小紅:";
int firstStartIndex = 0;
int firstBendIndex = str.indexOf("回覆");
int secondStartIndex = str.indexOf("回覆") + "回覆".length();
int secondBendIndex = str.indexOf(":");
SpannableString spannableString = new SpannableString(str);
spannableString.setSpan(new MyClickableSpan(new OnTextViewClickListener() {
@Override
public void setTextClick() {
Toast.makeText(MainActivity.this, "小明", Toast.LENGTH_SHORT).show();
}
}), firstStartIndex, firstBendIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new MyClickableSpan(new OnTextViewClickListener() {
@Override
public void setTextClick() {
Toast.makeText(MainActivity.this, "小紅", Toast.LENGTH_SHORT).show();
}
}), secondStartIndex, secondBendIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//設定點選文字後的文字背景色為透明
text_view.setHighlightColor(getResources().getColor(android.R.color.transparent));
text_view.setMovementMethod(LinkMovementMethod.getInstance());
text_view.setText(spannableString);
public interface OnTextViewClickListener {
void setTextClick();
}

private class MyClickableSpan extends ClickableSpan {
private OnTextViewClickListener onTextViewClickListener;
public MyClickableSpan(OnTextViewClickListener onTextViewClickListener) {
this.onTextViewClickListener = onTextViewClickListener;
}

@Override
public void updateDrawState(TextPaint ds) {
//super.updateDrawState(ds);
//ds.setColor()設定的是span超連結的文字顏色,而不是點選後的顏色,點選後的背景顏色(HighLightColor)屬於TextView的屬性,Android4.0以上預設是淡綠色,低版本的是黃色。
ds.setColor(Color.BLUE);
}

@Override
public void onClick(View widget) {
onTextViewClickListener.setTextClick();
}
}