Android text around image bug - android

By following this question, I was able to have text around an image. However, I have the following problem.
As you can see, the space for the image on top is displayed in every paragraph at the right. In the question someone had this problem and suggested to change 'ss.length()' for 'lines'. This seemed to work except if the first paragraph was too short, the next paragraph would overlap the image.
I modified the FlowTextHelper class slightly to use text from Html. This is the code I'm using:
public class FlowTextHelper {
private static boolean mNewClassAvailable;
/* class initialization fails when this throws an exception */
static {
try {
Class.forName("android.text.style.LeadingMarginSpan$LeadingMarginSpan2");
mNewClassAvailable = true;
} catch (Exception ex) {
mNewClassAvailable = false;
}
}
public static void tryFlowText(String text, View thumbnailView, TextView messageView, Display display, int addPadding){
// There is nothing I can do for older versions, so just return
if(!mNewClassAvailable) return;
// Get height and width of the image and height of the text line
thumbnailView.measure(display.getWidth(), display.getHeight());
int height = thumbnailView.getMeasuredHeight();
int width = thumbnailView.getMeasuredWidth() + addPadding;
messageView.measure(width, height); //to allow getTotalPaddingTop
int padding = messageView.getTotalPaddingTop();
float textLineHeight = messageView.getPaint().getTextSize();
// Set the span according to the number of lines and width of the image
int lines = (int)Math.round((height - padding) / textLineHeight);
//SpannableString ss = new SpannableString(text);
//For an html text you can use this line:
if(!text.equals("")) {
SpannableStringBuilder ss = (SpannableStringBuilder) Html.fromHtml(text);
ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(), 0);
messageView.setText(ss);
messageView.setMovementMethod(LinkMovementMethod.getInstance()); // links
// Align the text with the image by removing the rule that the text is to the right of the image
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) messageView.getLayoutParams();
int[] rules = params.getRules();
rules[RelativeLayout.RIGHT_OF] = 0;
}
}
}
public class MyLeadingMarginSpan2 implements LeadingMarginSpan.LeadingMarginSpan2 {
private int margin;
private int lines;
public MyLeadingMarginSpan2(int lines, int margin) {
this.margin = margin;
this.lines = lines;
}
#Override
public int getLeadingMargin(boolean first) {
return first ? margin : 0;
}
#Override
public int getLeadingMarginLineCount() {
return lines;
}
#Override
public void drawLeadingMargin(Canvas c, Paint p, int x, int dir,
int top, int baseline, int bottom, CharSequence text,
int start, int end, boolean first, Layout layout) {}
}
What is causing the space being repeated every paragraph and how can I get rid of it? Any help is appreciated.

I've spend hours to solve this issue, but solved it with thanks to the answer found here:
text wrapping around image in android
Basically as follows:
First add a margin to your textview and set the text
final RelativeLayout.LayoutParams params = RelativeLayout.LayoutParams)messageView.getLayoutParams();
params.setMargins(marginWidth, 0, 0, 0);
messageView.setText(Html.fromHtml(text));
Then add an OnGlobalLayoutListener and in the onGlobalLayout() call you calculate how many lines actually need the margin. You split the lines in 2 separate spannables and add the Margin only to the first one:
messageView.getViewTreeObserver().addOnGlobalLayoutListener( new OnGlobalLayoutListener() {
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
int linesCount = messageView.getLayout().getLineCount();
// restore the margin
params.setMargins(0, 0, 0, 0);
SpannableString spanS = new SpannableString ( Html.fromHtml(text) );
if (linesCount <= lines) {
spanS.setSpan(new MyLeadingMarginSpan2(lines, width), 0, spanS.length(), 0);
messageView.setText(spanS);
} else {
// find the breakpoint where to break the String.
int breakpoint = messageView.getLayout().getLineEnd(lines-1);
Spannable s1 = new SpannableStringBuilder(spanS, 0, breakpoint);
s1.setSpan(new MyLeadingMarginSpan2(lines, width), 0, s1.length(), 0);
Spannable s2 = new SpannableStringBuilder(System.getProperty("line.separator"));
Spannable s3 = new SpannableStringBuilder(spanS, breakpoint, spanS.length());
// It is needed to set a zero-margin span on for the text under the image to prevent the space on the right!
s3.setSpan(new MyLeadingMarginSpan2(0, 0), 0, s3.length(), 0);
messageView.setText(TextUtils.concat(s1, s2, s3));
}
// remove the GlobalLayoutListener
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
messageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
messageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});

If you need to wrap text around an image, use this library FlowTextView.
The library performs well, and it can be used with a couple lines. However, it does not support screen pixel size for fonts. I found a workaround with this answer, so that you can convert pixel size to sp.
I hope this helps anyone and you don't waste as much time as me using the question from my original post.

Related

Android: create a drawable that shows two lines of text one above the other in different fonts and sizes?

I want to create a single drawable that shows two lines of text, one above the other. Each line of text has to be in it's own typeface and textsize and it has to create a single drawable because I want to then set it as the drawable for a floating action button.
private void updateFloatingButtonText(String headlineText, String subHeadlineText, FloatingActionButton floatingActionButton) {
int headlineTextSize = getResources().getDimensionPixelSize(R.dimen.headlineTextSize);
int subheadlineTextSize = getResources().getDimensionPixelSize(R.dimen.subheadlineTextSize);
Spannable spannableStringHeadline = new SpannableString(headlineText);
Spannable spannableStringSubheadline = new SpannableString(subHeadlineText);
CustomTypefaceSpan boldSpan = new CustomTypefaceSpan("FontOne", FontCache.get("FontOne.ttf", this));
CustomTypefaceSpan regularSpan = new CustomTypefaceSpan("FontTwo", FontCache.get("FontTwo.ttf", this));
// set typeface headline
spannableStringHeadline.setSpan(regularSpan, 0,
headlineText.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE
);
// set typeface subtitle
spannableStringSubheadline.setSpan(boldSpan, 0,
subHeadlineText.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE
);
// set text size headline
spannableStringHeadline.setSpan(new AbsoluteSizeSpan(headlineTextSize), 0,
headlineText.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE
);
// set text size subline
spannableStringSubheadline.setSpan(new AbsoluteSizeSpan(subheadlineTextSize), 0,
subHeadlineText.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE
);
String finalString = TextUtils.concat(spannableStringHeadline, "\n", spannableStringSubheadline);
floatingActionButton.setImageDrawable([put the resulting drawable here]);
}
I've written this method that creates a single string formatted exactly the way that I need it, but I still have the issue of creating a drawable out of it.
I've tried to use this third party library, but although it displays the text in the correct typefaces it doesn't change the textsize of the lines of text.
https://github.com/devunwired/textdrawable
Is there a trivial (or nontrivial) way of doing this?
Solved by creating a new class that looks like this:
public class TextToDrawable extends Drawable {
private String headlineText = "";
private String subHeadlineText = "";
private final TextPaint headlinePaint = new TextPaint();
private final TextPaint subHeadlinePaint = new TextPaint();
public TextToDrawable(Context context, String headlineText, String subHeadlineText) {
this.headlineText = headlineText;
headlinePaint.setAntiAlias(true);
headlinePaint.setTypeface(FontCache.get("FontA.ttf", context));
headlinePaint.setTextSize(context.getResources().getDimensionPixelSize(R.dimen.headlineTextSize));
headlinePaint.setColor(ContextCompat.getColor(context, android.R.color.white));
headlinePaint.setStyle(Paint.Style.FILL);
headlinePaint.setTextAlign(Paint.Align.LEFT);
this.subHeadlineText = subHeadlineText;
subHeadlinePaint.setAntiAlias(true);
subHeadlinePaint.setTypeface(FontCache.get("FontB.ttf", context));
subHeadlinePaint.setTextSize(context.getResources().getDimensionPixelSize(R.dimen.subheadlineTextSize));
subHeadlinePaint.setColor(ContextCompat.getColor(context, android.R.color.white));
subHeadlinePaint.setStyle(Paint.Style.FILL);
subHeadlinePaint.setTextAlign(Paint.Align.LEFT);
}
#Override
public void draw(Canvas canvas) {
Rect headlineWidth = new Rect();
Rect subheadlineWidth = new Rect();
headlinePaint.getTextBounds(headlineText, 0, headlineText.length(), headlineWidth);
subHeadlinePaint.getTextBounds(subHeadlineText, 0, subHeadlineText.length(), subheadlineWidth);
Rect bounds = new Rect();
headlinePaint.getTextBounds(headlineText, 0, headlineText.length(), bounds);
int x = getBounds().width() / 2 - (headlineWidth.width()/2);
int y = (getBounds().height() / 2);
canvas.drawText(headlineText, x, y, headlinePaint);
x = getBounds().width()/2 - (subheadlineWidth.width()/2);
y += headlinePaint.getFontSpacing();
canvas.drawText(subHeadlineText, x, y, subHeadlinePaint);
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(ColorFilter colorFilter) {
}
#Override
public int getOpacity() {
return 0;
}
}
Then using the new class like this:
mFloatingActionButton.setImageDrawable(new TextToDrawable(this, "Headline", "Subheadline"));
This isn't a great solution because it only supports two lines of text - there's nothing dynamic going on here. However, I suppose it would be fairly easy to rewrite to support even more lines and more fonts and it solves the current problem.

How a content with multiple text views and image views break into pages instead of using a scroll view in android

I am implementing an epub reader for android. I have successfully read the epub files and got the content to dynamic textviews and imageviews. So the content is actually made up with multiple textviews and imageviews.
Currently I have used a scrollview to read the book. Now I need to break the whole content in to pages(content of a page should based on the screen size).
For this I am thinking of using ViewPager. So it can be used to swipe between pages easily. But if you have solutions for other than that I will be a great help.
can anyone help to achieve this?
Thanks.
Here is something to get you started with, the following component measures the text to fill the screen and the addTextmethod returns the text which was not fitted.
Combining with ImageView adds more complexity for measuring the height so I just made it to work with text. You could also adjust the values how many characters are removed to get iteration faster and also check for possibilities if this could be done more efficiently with line count combined with line height.
Notice that the component wants a long string which it will substring to whats left for next page.
public class ReaderLinearLayout extends LinearLayout {
private static final int TEXT_SIZE = 44;
private final DisplayMetrics dm = new DisplayMetrics();
public ReaderLinearLayout(Context context) {
super(context);
}
public ReaderLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public String addText(String text) {
int height = getScreenHeight();
String textLeftFromEnd = text;
int textHeight = getTextHeight(text);
while (textHeight > height) {
text = text.substring(0, text.length() - 1);
textHeight = getTextHeight(text);
}
TextView textView = new TextView(getContext());
textView.setText(text);
textView.setTextColor(Color.BLACK);
textView.setTextSize(TEXT_SIZE);
addView(textView);
return textLeftFromEnd.subSequence(text.length(),
textLeftFromEnd.length()).toString();
}
public int getTextHeight(final String text) {
TextView textView = new TextView(getContext());
textView.setText(text);
textView.setTextSize(TEXT_SIZE);
TextPaint textPaint = textView.getPaint();
return new StaticLayout(text.toString(), textPaint, getScreenWidth(),
Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true).getHeight();
}
public int getScreenHeight() {
WindowManager wm = (WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(dm);
return dm.heightPixels;
}
public int getScreenWidth() {
WindowManager wm = (WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(dm);
return dm.widthPixels;
}
}

text wrapping around image in android

I am using list view to show image and text i want to show like above image, can anyone suggest me how to wrap text around image with out webview. I am using following code:
Drawable dIcon = getResources().getDrawable(R.drawable.video_icon);
int leftMargin = dIcon.getIntrinsicWidth() + 10;
ImageView icon = (ImageView) findViewById(R.id.icon);
icon.setBackgroundDrawable(dIcon);
SpannableString ss = new SpannableString(text);
ss.setSpan(new MyLeadingMarginSpan2(3, leftMargin), 0, ss.length(), 0);
TextView messageView = (TextView) findViewById(R.id.message_view);
messageView.setText(ss);
class
class MyLeadingMarginSpan2 implements LeadingMarginSpan2 {
private int margin;
private int lines;
MyLeadingMarginSpan2(int lines, int margin) {
this.margin = margin;
this.lines = lines;
}
#Override
public int getLeadingMargin(boolean first) {
if (first) {
return margin;
} else {
return 0;
}
}
#Override
public void drawLeadingMargin(Canvas c, Paint p, int x, int dir,
int top, int baseline, int bottom, CharSequence text,
int start, int end, boolean first, Layout layout) {}
#Override
public int getLeadingMarginLineCount() {
return lines;
}
};
by using this code iam getting below image pls suggest to how to get first means correct wrapping text around image without more empty spaces
Older post, but since there is no accepted answer and I have just found solution for same problem in my app, I will post a solution.
I have discovered that text without any line break works well.
Text with a line break that splits the text into 2 parts in a way that the part before line break ends to the right of the image, and the part after line break starts already on next line bellow the image, this also works well.
So what I do is I set left margin of the wrapping TextView's LayoutParams to the desired indent, and I set the text into TextView. Then I add OnGlobalLayoutListener, and inside onGlobalLayout callback, I count the position of the last character on the last line to the right of the image
//lines - number of lines to be affected by the leadingMargin
int charCount = textView.getLayout().getLineEnd(Math.min(lines - 1, textView.getLayout().getLineCount() - 1));
If the text does not have more lines than the number of lines that should have the left margin (or if the last character is already line break), I just set the LeadingMarginSpan2 on the whole length of the text.
// s - original Spannable containing the whole text
if (charCount >= s.length() || charCount <= 0 || s.charAt(charCount - 1) == '\n') {
s.setSpan(new MyLeadingMarginSpan(lines, w), 0, charCount, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(s);
}
If the text is longer, I split it into 2 parts (first one ending at the charCount position), insert line break between them, merge them and set the LeadingMarginSpan2 only on the first part.
else {
Spannable s1 = new SpannableStringBuilder(s, 0, charCount);
s1.setSpan(new MyLeadingMarginSpan(lines, w), 0, charCount, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Spannable s2 = new SpannableStringBuilder(System.getProperty("line.separator"));
Spannable s3 = new SpannableStringBuilder(s, charCount, s.length());
textView.setText(TextUtils.concat(s1, s2, s3));
}
At the end, do not forget to remove the left margin of the TextView's LayoutParams.

If a text in a TextView is longer than the available space, how to get the remaining lines?

I have a long text and i want it to be displayed with a TextView. The text i have is much longer than the available space. However i don't want to use scrolling, but ViewFlipper to flip to the next page. How can i retrieve the lines from the first TextView that are not shown because the view is to short so that i can paste them into the next TextView?
Edit: I found the Solution to my Problem. I simply have to use a custom View with a StaticLayout like this:
public ReaderColumView(Context context, Typeface typeface, String cText) {
super(context);
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
dWidth = display.getWidth();
dHeight = display.getHeight();
contentText = cText;
tp = new TextPaint();
tp.setTypeface(typeface);
tp.setTextSize(25);
tp.setColor(Color.BLACK);
tp.setAntiAlias(true);
StaticLayout measureLayout = new StaticLayout(contentText, tp, 440, Alignment.ALIGN_NORMAL, 1, 2, true);
Boolean reachedEndOfScreen = false;
int line = 0;
while (!reachedEndOfScreen) {
if (measureLayout.getLineBottom(line) > dHeight-30) {
reachedEndOfScreen = true;
fittedText = contentText.substring(0, measureLayout.getLineEnd(line-1));
setLeftoverText(contentText.substring(measureLayout.getLineEnd(line-1)));
}
line++;
}
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
StaticLayout textLayout = new StaticLayout(fittedText, tp, 440, Alignment.ALIGN_NORMAL, 1, 2, true);
canvas.translate(20,20);
textLayout.draw(canvas);
}
Thats not optimized yet but you get the point.
I hope it might help somebody like me with a similar problem.
As in your answer you can use StaticLayout to measure and draw the text. However,
You should not create a StaticLayout during onDraw, it is very expensive, especially for long text. Instead you should create it once during onMeasure and reuse it.
For your while loop looking for the line to end (while (!reachedEndOfScreen)), you can use StaticLayout.getLineForVertical(int offset).
Instead of substring, or leftOverText you can use indices and pass those indices to StaticLayout for each page.

How to find out if TextView text content has been cut off

I can set max line in my TextView in layout xml file.
In my code, after I call setText() to the TextView, how can I find out if the text content has been cut off (i.e. the text is longer than the max line)?
Thank you.
So while I haven't tested this yet (sorry no sdk setup in front of me)
Your TextView should have a Paint object created for it. Now I would assume that TextPaint has been constructed with the correct padding and offset for the background image of the text view. So you should be able to do something like
TextView a = getViewById(R.id.textview);
TextPaint paint = a.getPaint();
Rect rect = new Rect();
String text = String.valueOf(a.getText());
paint.getTextBounds(text, 0, text.length(), rect);
if(rect.height() > a.getHeight() || rect.width() > a.getWidth()) {
Log.i("TEST", "Your text is too large");
}
I know this is an old question, but I came across it in my search for a similar answer and wanted to offer the solution that I found, in case anyone else is wondering.
This worked for me:
TextView myTextView = rootView.getViewById(R.id.my_text_view);
if (myTextView.getLineCount() > myTextView.getMaxLines()) {
// your code here
}
Try this:
mTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ViewTreeObserver obs = mTextView.getViewTreeObserver();
obs.removeOnGlobalLayoutListener(this);
int height = mTextView.getHeight();
int scrollY = mTextView.getScrollY();
Layout layout = mTextView.getLayout();
int firstVisibleLineNumber = layout.getLineForVertical(scrollY);
int lastVisibleLineNumber = layout.getLineForVertical(height + scrollY);
//check is latest line fully visible
if (mTextView.getHeight() < layout.getLineBottom(lastVisibleLineNumber)) {
// TODO you text is cut
}
}
});

Categories

Resources