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

前端 未结 3 1707
耶瑟儿~
耶瑟儿~ 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:51

    Graphics.getFontMetrics and FontMetrics.stringWidth will help you to determine real size of text on the screen. Based on this calculation you can determine how long shown substring should be.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2021-02-04 15:14

    if each part has a different number of characters , they will also need to have different size of fonts . not only that , but too small devices will also have a too small font size , since the text need to fit a smaller space. i'd suggest having the same font size for all of the parts , while allowing to scroll down if there is not enough space.

    for this , you can use a viewpager with scrollviews on each page , each contain a textview.

    0 讨论(0)
提交回复
热议问题