android覆盖textView以设置基于getMaxLines的文本



我有一个扩展TextView的customTextView。

我想覆盖setText,这样如果某个文本长度大于最大行数,那么我必须显示其他文本,而不是getText中的文本。

这是我的代码

public class CustomTextView extends TextView {
    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        setLinksClickable(true);
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        String text = String.valueOf(getText());
        Spanned htmlFormatedText = OmniTextUtil.getHyperLinked(text);
        setText(htmlFormatedText);
        List<CharSequence> charSequenceList = getLines(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
        {
            if(getLineCount() > getMaxLines())
            {
                for(int i =0; i < getMaxLines(); i++)
                {
                    text = text + charSequenceList.get(i);
                }
                text = text.substring(0, text.length() -3) + "...";
                setText(text);
            }
        }
    }
    public static List<CharSequence> getLines(TextView view) {
        final List<CharSequence> lines = new ArrayList<>();
        final Layout layout = view.getLayout();
        if (layout != null) {
            // Get the number of lines currently in the layout
            final int lineCount = layout.getLineCount();
            // Get the text from the layout.
            final CharSequence text = layout.getText();
            // Initialize a start index of 0, and iterate for all lines
            for (int i = 0, startIndex = 0; i < lineCount; i++) {
                // Get the end index of the current line (use getLineVisibleEnd()
                // instead if you don't want to include whitespace)
                final int endIndex = layout.getLineEnd(i);
                // Add the subSequence between the last start index
                // and the end index for the current line.
                lines.add(text.subSequence(startIndex, endIndex));
                // Update the start index, since the indices are relative
                // to the full text.
                startIndex = endIndex;
            }
        }
        return lines;
    }
}

我可以设置我的文本,但在滚动时,它会变成普通文本。。。

如果您只想在文本末尾添加三条虚线,那么您可以简单地完成。尝试低于代码

//程序化

        text_view.setEllipsize(TextUtils.TruncateAt.END);
        text_view.setMaxLines(2);//set number of line what ever you want.
        text_view.setText("your long text");

//使用xml

 <TextView
            android:id="@+id/tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:lines="2"
            android:maxLines="2"
            android:text="your long text"
            android:textColor="@android:color/black" />

如果你想检查文本是否太长,请尝试这个链接。希望它能帮助你。

最新更新