您可以使用此方法来实现此目的
public void doEllipsize(final TextView tv, final int maxLine) {
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
ViewTreeObserver obs = tv.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
if (maxLine <= 0) {
int lineEndIndex = tv.getLayout().getLineEnd(0);
String text = tv.getText().subSequence(0, lineEndIndex - 3)
+ "...";
tv.setText(text);
} else if (tv.getLineCount() >= maxLine) {
int lineEndIndex = tv.getLayout().getLineEnd(maxLine - 1);
String text = tv.getText().subSequence(0, lineEndIndex - 3)
+ "...";
tv.setText(text);
}
}
});
}
如何使用
将此方法放入您的活动中并在 findViewById() 之后调用
TextView yourTv = (TextView)findViewById(R.id.yourtv);
doEllipsize(yourTv,2);