How to use custom ellipsis in Android TextView

前端 未结 5 1774
陌清茗
陌清茗 2020-12-31 09:55

I have a TextView with maxlines=3 and I would like to use my own ellipsis, instead of

\"Lore ipsum ...\"

I need

\"Lore ips         


        
5条回答
  •  有刺的猬
    2020-12-31 10:31

    I've finally managed it in this way (may be not the best one):

    private void setLabelAfterEllipsis(TextView textView, int labelId, int maxLines){
    
        if(textView.getLayout().getEllipsisCount(maxLines-1)==0) {
            return; // Nothing to do
        }
    
        int start = textView.getLayout().getLineStart(0);
        int end = textView.getLayout().getLineEnd(textView.getLineCount() - 1);
        String displayed = textView.getText().toString().substring(start, end);
        int displayedWidth = getTextWidth(displayed, textView.getTextSize());
    
        String strLabel = textView.getContext().getResources().getString(labelId);
        String ellipsis = "...";
        String suffix = ellipsis + strLabel;
    
        int textWidth;
        String newText = displayed;
        textWidth = getTextWidth(newText + suffix, textView.getTextSize());
    
        while(textWidth>displayedWidth){
            newText = newText.substring(0, newText.length()-1).trim();
            textWidth = getTextWidth(newText + suffix, textView.getTextSize());
        }
    
        textView.setText(newText + suffix);
    }
    
    private int getTextWidth(String text, float textSize){
        Rect bounds = new Rect();
        Paint paint = new Paint();
        paint.setTextSize(textSize);
        paint.getTextBounds(text, 0, text.length(), bounds);
    
        int width = (int) Math.ceil( bounds.width());
        return width;
    }
    

提交回复
热议问题