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