Set Text View ellipsize and add view more at end

前端 未结 13 1197

I am trying to set ellipsize of text view. using the following code. I want to add \"view more\" at the end of truncated string after 3 dots. If this would be possible with

13条回答
  •  借酒劲吻你
    2020-12-02 13:26

    Simpler than the accepted answer:

    public static final int MAX_LINES = 3;
    
    String myReallyLongText = "Bacon ipsum dolor amet porchetta venison ham fatback alcatra tri-tip, turducken strip steak sausage rump burgdoggen pork loin. Spare ribs filet mignon salami, strip steak ball tip shank frankfurter corned beef venison. Pig pork belly pork chop andouille. Porchetta pork belly ground round, filet mignon bresaola chuck swine shoulder leberkas jerky boudin. Landjaeger pork chop corned beef, tri-tip brisket rump pastrami flank."
    
    textView.setText(myReallyLongText);
    textView.post(new Runnable() {
                    @Override
                    public void run() {
                        // Past the maximum number of lines we want to display.
                        if (textView.getLineCount() > MAX_LINES) {
                            int lastCharShown = textView.getLayout().getLineVisibleEnd(MAX_LINES - 1);
    
                            textView.setMaxLines(MAX_LINES);
    
                            String moreString = context.getString(R.string.more);
                            String suffix = TWO_SPACES + moreString;
    
                            // 3 is a "magic number" but it's just basically the length of the ellipsis we're going to insert
                            String actionDisplayText = myReallyLongText.substring(0, lastCharShown - suffix.length() - 3) + "..." + suffix;
    
                            SpannableString truncatedSpannableString = new SpannableString(actionDisplayText);
                            int startIndex = actionDisplayText.indexOf(moreString);
                            truncatedSpannableString.setSpan(new ForegroundColorSpan(context.getColor(android.R.color.blue)), startIndex, startIndex + moreString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            textView.setText(truncatedSpannableString);
                        }
                    }
                });
    

提交回复
热议问题