How to get N text that can be fit on Screen/TextView with a specific size?

前端 未结 3 1713
耶瑟儿~
耶瑟儿~ 2021-02-04 14:42

I have a large story in String format. I want to show the text in gallery. What I want to do is to slice all the text in such a way that all my view in gallery show the text whi

3条回答
  •  太阳男子
    2021-02-04 14:58

    You check the TextView source code and see how they decide where to ellipsize the string.

    The code for TextView is here.

    Alternatively, you can use TextUtils class's public static CharSequence ellipsize(CharSequence text, TextPaint p, float avail, TruncateAt where) method.

    TextPaint p should be the TextView's paint object.

    Update:

    Another alternative is to use Paint.getTextWidths(char[] text, int index, int count, float[] widths).

    textpaint.getTextWidths(char[] text, int index, int count, float[] widths);
    
    int i = 0;
    int prev_i = 0;
    while (i < count) {
        textWidth = 0;
        for (int i = prev_i; (i < count) || (textWidth < availableWidth); i++) {
            textWidth += widths[i];
        }
        String textThatFits = mOriginalText.subString(prev_i, i);
        mTextview.setText(textThatFits);
        prev_i = i;
    }
    

    i is the number of characters that fit in the TextView.
    availableWidth is the width of the TextView in pixels.

    This code is approximate and contains syntax errors. You will have to do some minor changes to get it working.

    Update 2:

    Another alternative would be to use

    int breakText (CharSequence text,      
                    int start, int end,   
                    boolean measureForwards,   
                    float maxWidth, float[] measuredWidth). 
    

    I think this is the best solution for you. Check its documentation here.

    Update:

    Sample code using paint.breakText method.

    paint.setSubpixelText(true);
    int prevPos = 0;
    while (nextPos  < chars.length) {
        int nextPos = paint.breakText(chars, prevPos, chars.length, maxWidth, null);
        tvStr = str.substring(prevPos, nextPos);
        prevPos = nextPos+1;
    }
    

提交回复
热议问题