TextView: Add text after ellipsis or change ellipsis character

后端 未结 1 1272
野性不改
野性不改 2020-12-19 06:03

What I am trying to do

I am trying to have a TextView with

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

that i

相关标签:
1条回答
  • 2020-12-19 06:57

    Try this way

    create this function

    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);
                    }
                }
            });
    
        }
    

    how to use

    This will write "SeeMore" instead "..." at the end of 4th line

    makeTextViewResizable(tv, 4, "SeeMore");
    

    Now not need to write these lines in xml

    android:ellipsize="end"
    android:maxLines="3"
    
    0 讨论(0)
提交回复
热议问题