Textview內容過多,尾部顯示省略號或【更多】

一先看圖


二、TextView 內容過多,直接設置 maxLines 和ellipsize=end 效果如圖 上方TextView

三、尾部添加[更多內容],一開始想通過相對佈局實現,發現不太可能(若有解決方案歡迎指正)

四、解決方案:

public class AD01 extends Activity {
    TextView tv;
    String str = "舉個例子來說明一吧,爲了讓大家更明白一點,比如一個鉛筆盒中有一支筆,但在沒有打開之前你並不知道它是什麼筆,可能是鉛筆也可能是鋼筆,這裏有兩種可能,那麼你就可以定義一個枚舉類型來表示它";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ad02);
        tv = (TextView) findViewById(R.id.tttt);
        tv.setText(str);
        ViewTreeObserver observer = tv.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ViewTreeObserver obs = tv.getViewTreeObserver();
                obs.removeGlobalOnLayoutListener(this);
                if (tv.getLineCount() > 2) {
                  int lineEndIndex = tv.getLayout().getLineEnd(1);
                  String html = tv.getText().subSequence(0, lineEndIndex -6)
                         + "……<font color='#ff0000'>[更多內容]</font>";
                    tv.setText(Html.fromHtml(html));
                }
            }
        });
    }
}

QQ羣裏小夥伴idea 寫了一個自定義控件

public class AutoTextView extends TextView  {
private int tagTextColor = 0xFFFF0000;
private String tag = "...[更多內容]";
public AutoTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
ViewTreeObserver viewTreeObserver = getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(this);
 setText(getText().toString());
}
public AutoTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AutoTextView(Context context) {
this(context, null);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
@Override
public boolean onPreDraw() {
replaceText();
return super.onPreDraw();
}
public void replaceText() {
int count=getLineCount();
if(count>2){
int st=getLayout().getLineEnd(1);
String content = getText().toString().substring(0,st);
Paint paint = new Paint();
paint.setTextSize(getTextSize());
float pointWidth = paint.measureText(tag);
char[] textCharArray = content.toCharArray();
float drawedWidth = 0;
float charWidth;
for (int i = textCharArray.length-1; i >0 ; i--) {
charWidth = paint.measureText(textCharArray, i, 1);
if (drawedWidth < pointWidth ) {
drawedWidth += charWidth;
} else {
content=content.substring(0,i)+tag;
break;
}
}

setColor(content, content.length()-6, content.length(), tagTextColor);
}
}
private void setColor(String content, int start, int end, int textColor) {
if (start <= end) {
SpannableStringBuilder style = new SpannableStringBuilder(content);
style.setSpan(new ForegroundColorSpan(textColor), start, end,
Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
setText(style);
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章