美文网首页Android开发
类似显示全文的实现

类似显示全文的实现

作者: 这人可能是刘文亮 | 来源:发表于2019-01-23 16:50 被阅读4次

需求是textview最多显示两行,末尾显示一个icon。
当文字过长被截断时,要显示「文字...{图片}」的效果;
文字长度可以显示完全时,图片位置在文本最后一个字的后面。

不要手动拼接字符串「...」,因为不同手机上可能显示的大小不一样。
可以用sdk方法TextUtils.ellipsize自动截取,或者拼接new String({'\u2025' })

代码中的textviewWidthView是一个透明的高度为1dp的view,宽度是match_parent的。
作用是获取textview的最大宽度。因为textview的宽度是wrap_content的。

做法是,用textview宽度计算能显示多少文字,如果实际文字长度大于能显示的文字长度,末尾截断,然后富文本拼接icon。
如果末尾要显示的是其他形式的,例如显示全文,思路是一样的。

        StringBuilder resultContent = new StringBuilder("");
        String content = "xxx";
        int textWidth = textviewWidthView.getMeasuredWidth();
        int textSecondLineWidth = textWidth - LayoutUtils.dpToPx(getContext(), 18);
        float[] measuredWidth = new float[1];
        int firstLine = textview.getPaint().breakText(content, true, textWidth, measuredWidth);
        resultContent.append(content.substring(0, firstLine));
        if (content.length() > firstLine) {
            String secondLineContent = content.substring(firstLine);
            int secondLine = textview.getPaint().breakText(secondLineContent, true, textSecondLineWidth, measuredWidth);
            if (secondLineContent.length() > secondLine) {
                String elipText = (String) TextUtils.ellipsize(secondLineContent, textview.getPaint(), textSecondLineWidth, TextUtils.TruncateAt.END);
                resultContent = resultContent.append(elipText);
            } else {
                resultContent.append(secondLineContent.substring(0, secondLine));
            }
        }
        resultContent.append(" ");
        SpannableString res = new SpannableString(resultContent);
        Drawable drawable = getResources().getDrawable(R.drawable.icn_external_link);
        drawable.setBounds(0, 0, LayoutUtils.dpToPx(getContext(), 18), LayoutUtils.dpToPx(getContext(), 14));
        ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
        res.setSpan(imageSpan, resultContent.length() - 1, resultContent.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        textview.setText(res);

相关文章

网友评论

    本文标题:类似显示全文的实现

    本文链接:https://www.haomeiwen.com/subject/resjjqtx.html