TextView 设置显示省略号

限制TextView显示的字符数,多出的部分显示省略号。

效果图如下:TextView 设置显示省略号_第1张图片



自定义EllipsizingTextView.java,(com.example.user.helloworld.EllipsizingTextView)内容如下:

public class EllipsizingTextView extends TextView {
    private static final String ELLIPSIS = "...";

    private boolean isStale;
    private boolean programmaticChange;
    private String fullText;
    private int maxLength = -1;

    public EllipsizingTextView(Context context) {
        super(context);
    }

    public EllipsizingTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EllipsizingTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * 外部通过调用setMaxLength方法设置显示的最多字数为maxLength
     * @param maxLength
     */
    public void setMaxLength(int maxLength) {
        this.maxLength = maxLength;
    }

    public int getMaxLength(){
        return maxLength;
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int before, int after) {
        super.onTextChanged(text, start, before, after);
        if (!programmaticChange) {
            fullText = text.toString();
            isStale = true;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (isStale) {
            super.setEllipsize(null);
            resetText();
        }
        super.onDraw(canvas);
    }

    private void resetText() {
        int len = fullText.length();
        String workingText = fullText;
        if (maxLength != -1) {
            if (len > maxLength) {
                workingText = fullText.substring(0, maxLength).trim();
                workingText = workingText + ELLIPSIS;
            }
        }
        if (!workingText.equals(getText())) {
            programmaticChange = true;
            try {
                setText(workingText);
            } finally {
                programmaticChange = false;
            }
        }
        isStale = false;
    }

}


如何使用呢?

1. Activity布局文件actiivty_main.xml中使用此自定义TextView,如下:


2. 在Activity代码中获取EllipsizingTextView对象,首先定义EllipsizingTextView对象。

 
  
private EllipsizingTextView tv_content;
3.在onCreate(Bundle savedInstanceState)方法中获取tv_content对象,如下:
 
  
tv_content = (EllipsizingTextView) findViewById(R.id.tv_content);
4.设置最多显示字符数(设置最多显示120字符,超出部分使用省略号显示),如下:
 
  
tv_content.setMaxLength(120);
通过这种方式,适用于当行和多行的情况。

如果单行文本显示不完整末尾显示省略号,就简单多了。
只需要在activity的布局文件,TextView节点添加属性:android:singleLine="true"和android:ellipsize="end"即可,如下:
 
  
android:singleLine="true"
    android:text="Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发。"
    android:ellipsize="end"/>
 
  
如果限制显示指定的行数,超出指定的行数显示省略号。已经有人自定义了
EllipsizingTextView类。
原文地址:http://code.taobao.org/p/android_jiudu/src/trunk/Forlind/src/com/wine/jiubang/ui/view/EllipsizingTextView.java 点击打开链接
代码如下:

package com.example.user.helloworld;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

    public class EllipsizingTextView extends TextView {

        private static final String ELLIPSIS = "...";

        public interface EllipsizeListener {
            void ellipsizeStateChanged(boolean ellipsized);
        }

        private final List ellipsizeListeners = new ArrayList();

        private boolean isEllipsized;
        private boolean isStale;
        private boolean programmaticChange;
        private String fullText;
        private int mMaxLines = -1;
        private float lineSpacingMultiplier = 1.0f;
        private float lineAdditionalVerticalPadding = 0.0f;

        public EllipsizingTextView(Context context) {
            super(context);
        }

        public EllipsizingTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            // 开始没加这两行的时候,一直不对,maxlinex在textChange里面会被改变为-1
            TypedArray a = context.obtainStyledAttributes(attrs, new int[] { android.R.attr.maxLines });
            setMaxLines(a.getInt(0, 2));
            a.recycle();
        }

        public EllipsizingTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            // 开始没加这两行的时候,一直不对,maxlinex在textChange里面会被改变为-1
            TypedArray a = context.obtainStyledAttributes(attrs, new int[] { android.R.attr.maxLines });
            setMaxLines(a.getInt(0, 2));
            a.recycle();
        }

        public void addEllipsizeListener(EllipsizeListener listener) {
            if (listener == null) {
                throw new NullPointerException();
            }
            ellipsizeListeners.add(listener);
        }

        public void removeEllipsizeListener(EllipsizeListener listener) {
            ellipsizeListeners.remove(listener);
        }

        public boolean isEllipsized() {
            return isEllipsized;
        }

        @Override
        public void setMaxLines(int maxLines) {
            super.setMaxLines(maxLines);
            this.mMaxLines = maxLines;
            isStale = true;
        }

        public int getMaxLine() {
            return mMaxLines;
        }

        public int getTextLines(){
            return createWorkingLayout(fullText).getLineCount();
        }
        @Override
        public void setLineSpacing(float add, float mult) {
            this.lineAdditionalVerticalPadding = add;
            this.lineSpacingMultiplier = mult;
            super.setLineSpacing(add, mult);
        }

        @Override
        protected void onTextChanged(CharSequence text, int start, int before, int after) {
            super.onTextChanged(text, start, before, after);
            if (!programmaticChange) {
                fullText = text.toString();
                isStale = true;
            }
        }

        @Override
        protected void onDraw(Canvas canvas) {
            if (isStale) {
                super.setEllipsize(null);
                resetText();
            }
            super.onDraw(canvas);
        }

        private void resetText() {
            int maxLines = getMaxLine();
            String workingText = fullText;
            boolean ellipsized = false;
            if (maxLines != -1) {
                Layout layout = createWorkingLayout(workingText);
                if (layout.getLineCount() > maxLines) {

                    workingText = fullText.substring(0, layout.getLineEnd(maxLines - 1)).trim();
                    Layout layout2 = createWorkingLayout(workingText + ELLIPSIS);
                    while (layout2.getLineCount() > maxLines) {
                        workingText = workingText.substring(0, workingText.length() - 1 - 1);
                        layout2 = createWorkingLayout(workingText + ELLIPSIS);
                    }
                    workingText = workingText + ELLIPSIS;
                    ellipsized = true;
                }
            }
            if (!workingText.equals(getText())) {
                programmaticChange = true;
                try {
                    setText(workingText);
                } finally {
                    programmaticChange = false;
                }
            }
            isStale = false;
            if (ellipsized != isEllipsized) {
                isEllipsized = ellipsized;
                for (EllipsizeListener listener : ellipsizeListeners) {
                    listener.ellipsizeStateChanged(ellipsized);
                }
            }
        }

        private Layout createWorkingLayout(String workingText) {
            return new StaticLayout(workingText, getPaint(), getWidth() - getPaddingLeft()
                    - getPaddingRight(), Layout.Alignment.ALIGN_NORMAL, lineSpacingMultiplier,
                    lineAdditionalVerticalPadding, false);
        }

        @Override
        public void setEllipsize(TextUtils.TruncateAt where) {
            // Ellipsize settings are not respected } }
        }
    }

使用方法:

1 Activity类的布局文件activity_main.xml使用此自定义View,如下:

2 Activity类查找该组件
private EllipsizingTextView tv_content = (EllipsizingTextView)findViewById(R.id.etv);
tv_content.setMaxLines(5);

最终实现的效果是:少于5行内容全部显示,超出5行内容不显示,且第5行末尾显示省略号。











你可能感兴趣的:(android基础)