我想將省略號字符串從...更改爲自定義字符串,例如abc...[more]
。 但在TextUtil,省略號字符串是固定的:如何更改Android TextView的省略號字符串?(...更多)
private static final String ELLIPSIS_STRING = new String(ELLIPSIS_NORMAL);
我想將省略號字符串從...更改爲自定義字符串,例如abc...[more]
。 但在TextUtil,省略號字符串是固定的:如何更改Android TextView的省略號字符串?(...更多)
private static final String ELLIPSIS_STRING = new String(ELLIPSIS_NORMAL);
試試這個方法
public void CustomEllipsize(final TextView tv, final int maxLine, final String ellipsizetext) {
if (tv.getTag() == null) {
tv.setTag(tv.getText());
}
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
ViewTreeObserver obs = tv.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
if ((maxLine+1) <= 0) {
int lineEndIndex = tv.getLayout().getLineEnd(0);
String text = tv.getText().subSequence(0, lineEndIndex - ellipsizetext.length()) + " " + ellipsizetext;
tv.setText(text);
} else if (tv.getLineCount() >= (maxLine+1)) {
int lineEndIndex = tv.getLayout().getLineEnd((maxLine+1) - 1);
String text = tv.getText().subSequence(0, lineEndIndex - ellipsizetext.length()) + " " + ellipsizetext;
tv.setText(text);
}
}
});
}
,並使用此方法像這樣
final TextView txtView = (TextView) findViewById(R.id.txt);
String dummyText = "sdgsdafdsfsdfgdsfgdfgdfgsfgfdgfdgfdgfdgfdgdfgsfdgsfdgfdsdfsdfsdf";
txtView.setText(dummyText);
CustomEllipsize(txtView, 2, "...[more]");
我找到了答案How to use custom ellipsis in Android TextView。但是你必須在佈局之後運行這個函數,你可以在OnGlobalLayoutListener.onGlobalLayout()或view.post()上運行它。
無論需要與否,它都會在最大行中省略。 –