为规避Android5.0以下系统省略号显示异常问题 增加设置文字内容方法,多出部分以省略号显示.
废话不多说直接上代码~
public class CustomTextView extends android.support.v7.widget.AppCompatTextView {
private static final String TAG = "CustomTextView";
public CustomTextView(Context context) {
this(context, null);
}
public CustomTextView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setEllipsize(null);
// setMaxEms(1);
}
/**
* 设置文字,超出部分以结尾省略号显示
* @param text 文字内容
*/
public void setEndText(CharSequence text) {
handleEndText(text);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
handleEndText(getText());
}
/**
* 处理内容超过宽度后,用省略号显示
* @param text 内容
*/
private void handleEndText(CharSequence text) {
MxLog.d(TAG, "handleEndText start = " + text);
Paint paint = getPaint();
if (!TextUtils.isEmpty(text)) {
int mAvailableWidth = getWidth() - getPaddingStart() - getPaddingEnd();
int textLength = (int) paint.measureText(text, 0, text.length());
if (textLength > mAvailableWidth) {
int textLastIndex = paint.breakText(text, 0, text.length(), true, mAvailableWidth - paint.measureText("…"), null);
text = text.subSequence(0, textLastIndex);
text = text + "…";
}
}
setText(text, BufferType.NORMAL);
MxLog.d(TAG, "handleEndText end = " + text);
}
}