android TextView查看更多(图文混排)

  效果如下:

android TextView查看更多(图文混排)_第1张图片


代码有很多注释,看懂应该没问题

/**
 * Created by sxy on 2016/11/10.
 */
public class TextUtils {


    public static void toggleEllipsize(final Context context, final TextView tv, final String desc) {
        if (desc == null) {
            return;
        }
        tv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                boolean isEllipsized = (tv.getTag() == null || tv.getTag().equals(false)) ? false : (Boolean) tv.getTag();
                if (isEllipsized) {
                    //第一次为TextView设置文字内容,触发这里的内容
                    tv.setTag(false);
                    tv.setText(desc);
                } else {
                    //设置原内容后触发下面的代码
                    tv.setTag(true);
                    int paddingLeft = tv.getPaddingLeft();
                    int paddingRight = tv.getPaddingRight();
                    TextPaint paint = tv.getPaint();
                    float moreText = tv.getTextSize() * 2;
                    //设置的可见内容长度,乘以2代表两行
                    float availableTextWidth = (tv.getWidth() - paddingLeft - paddingRight) * 2 - moreText;

                    //ellipsizeStr为原内容或者超过设置长度后被截取并加上省略号后的内容,所有两者要么长度一样要么desc大于ellipsizeStr
                    CharSequence ellipsizeStr = android.text.TextUtils.ellipsize(desc, paint, availableTextWidth, android.text.TextUtils.TruncateAt.END);
                    if (ellipsizeStr.length() < desc.length()) {
                        //需要设置查看更多时
                        //后面的“.”,可随意更改,主要为了做后面的替换,把该符号替换为图片或者“查看更多”
                        CharSequence temp = ellipsizeStr + ".";
                        SpannableStringBuilder ssb = new SpannableStringBuilder(temp);
                        Drawable dd = context.getResources().getDrawable(R.drawable.ic_arrow_down);
                        dd.setBounds(0, 0, dd.getIntrinsicWidth(), dd.getIntrinsicHeight());
                        ImageSpan is = new ImageSpan(dd, ImageSpan.ALIGN_BASELINE);
                        //把最后一位替换为图片,最后一位就是上面设置的那个“.”
                        ssb.setSpan(is, temp.length() - 1, temp.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                        tv.setText(ssb);
                        tv.setMovementMethod(LinkMovementMethod.getInstance());
                    } else {
                        //两者长度一样,说明设置的内容没有超过长度,不需要截取
                        tv.setText(desc);
                    }
                }
                if (Build.VERSION.SDK_INT >= 16) {
                    tv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });
    }
}


你可能感兴趣的:(android小例子)