通过kt改造
*/
public class EllipsizedTextView extends AppCompatTextView {
private SpannableString ellipsisSpannable;
private SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
String ellipsis;
int ellipsisColor;
private static final String ELLIPSIS_NORMAL = “\u2026”; // (…)
public EllipsizedTextView(Context context) {
this(context,null);
}
public EllipsizedTextView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public EllipsizedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
ellipsis = getDefaultEllipsis().toString();
ellipsisColor = getDefaultEllipsisColor();
if (attrs != null) {
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.EllipsizedTextView, 0, 0);
ellipsis = typedArray.getString(R.styleable.EllipsizedTextView_ellipsis);
ellipsisColor = typedArray.getColor(R.styleable.EllipsizedTextView_ellipsisColor, getDefaultEllipsisColor());
typedArray.recycle();
}
ellipsisSpannable = new SpannableString(ellipsis);
ellipsisSpannable.setSpan(new ForegroundColorSpan(ellipsisColor), 0, ellipsis.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
float availableScreenWidth = getMeasuredWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight();
float availableTextWidth = availableScreenWidth * getMaxLines();
String ellipsizedText = TextUtils.ellipsize(getText(), getPaint(), availableTextWidth, getEllipsize()).toString();
//如果裁剪后文字跟TextView文字不一致。需要执行替换逻辑。
if (ellipsizedText.toString() != getText().toString()) {
// If the ellipsizedText is different than the original text, this means that it didn’t fit and got indeed ellipsized.
// Calculate the new availableTextWidth by taking into consideration the size of the custom ellipsis, too.
//此处计算错误。应该是最后一行才有Ellipsize
// availableTextWidth = (availableScreenWidth - getPaint().measureText(ellipsis)) * getMaxLines();
if(getMaxLines()>=1) {
availableTextWidth = availableScreenWidth * (getMaxLines() - 1) + (availableScreenWidth - getPaint().measureText(ellipsis));
ellipsizedText = TextUtils.ellipsize(getText(), getPaint(), availableTextWidth, getEllipsize()).toString();
int defaultEllipsisStart = ellipsizedText.indexOf(getDefaultEllipsis());
int defaultEllipsisEnd = defaultEllipsisStart + 1;
spannableStringBuilder.clear();
// Update the text with the ellipsized version and replace the default ellipsis with the custom one.
setText(spannableStringBuilder.append(ellipsizedText).replace(defaultEllipsisStart, defaultEllipsisEnd, ellipsisSpannable));
}
}
}
private String getDefaultEllipsis() {
return ELLIPSIS_NORMAL;
}
private int getDefaultEllipsisColor() {
return getTextColors().getDefaultColor();
}
}