7

What I am trying to do

I am trying to have a TextView with

android:ellipsize="end"
android:maxLines="3"

that instead of the "..." has a "... Show More" at the end.

Where I am

If the TextView would be single line this would be easy as I could use 2 TextViews, but I need it to have multiple lines and the "Show More" needs to be inline.

I have been searching for a way to change the ellipsis character that is added at the end but could not find anything.

The only solution I can think of is giving up on the automatic ellipsis, measure text and add the "... Show More" from code.

The question

Is there a way to replace what Android adds at the end (the "...") with something custom?

4

1 回答 1

10

试试这个方法

创建这个函数

public  void makeTextViewResizable(final TextView tv, final int maxLine, final String expandText) {

        if (tv.getTag() == null) {
            tv.setTag(tv.getText());
        }
        ViewTreeObserver vto = tv.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout() {

                ViewTreeObserver obs = tv.getViewTreeObserver();
                obs.removeGlobalOnLayoutListener(this);
                if (maxLine <= 0) {
                    int lineEndIndex = tv.getLayout().getLineEnd(0);
                    String text = tv.getText().subSequence(0, lineEndIndex - expandText.length() + 1) + " " + expandText;
                    tv.setText(text);
                } else if (tv.getLineCount() >= maxLine) {
                    int lineEndIndex = tv.getLayout().getLineEnd(maxLine - 1);
                    String text = tv.getText().subSequence(0, lineEndIndex - expandText.length() + 1) + " " + expandText;
                    tv.setText(text);
                }
            }
        });

    }

如何使用

这将在第 4 行末尾写“SeeMore”而不是“...”

makeTextViewResizable(tv, 4, "SeeMore");

现在不需要在xml中写这些行

android:ellipsize="end"
android:maxLines="3"
于 2013-09-11T10:04:27.313 回答