Wednesday, June 17, 2009

How to have a few layout elements wrap around

Here is a problem people might encounter when dealing with layouts on android.

Say you want to place an image at the middle of a sentence. you may add a couple TextView and an ImageView but if the horizontal space gets too small the two TextViews are going to start wrapping around independently wich is going to look weird. You'd want the image to be part of your TextView and the entire sentence to wrap around nicely.

To do so:
* replace the three objects by one Spannable TextView
* use a SpannableStringBuilder to append all your strings (don't forget to add an extra character (a space for example) that will be replaced by your image)
* and finally use setSpan(ImageSpan, begin, end, flag) on that builder where ImageSpan is an ImageSpan containing the drawable of your picture, begin is the index of the character you've inserted

So instead of having something that looks like this:
I really really really really like Posted by Picasa Picasa because it's a very very very very nice free image editing software

You get something that looks more like that:
I really really really really like Posted by Picasa Picasa because it's a very very very very nice free image editing software

And here's what the code would look like:

add android:bufferType="spannable" to your TextView

SpannableStringBuilder builder
= new SpannableStringBuilder();
builder.append(mContext.getText(R.string.part1));
int lengthOfPart1 = builder.length();
builder.append(" ");
builder.append(mContext.getText(R.string.part2));
Drawable d = mContext.getResources().getDrawable(R.drawable.picasaIcon);
d
.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); // <---- Very important otherwise your image won't appear
ImageSpan myImage = new ImageSpan(d
);
builder.setSpan(myImage, lengthOfPart1, lengthOfPart1 + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myTextView.setText(builder);

4 comments:

  1. Spannable looks very useful. I wanted to do exactly this a few times while writing my app, but didn't know how. Thanks for posting this!

    ReplyDelete
  2. Thanks a lot, I searched for a solution, I found !!
    Really usefull

    ReplyDelete
  3. sweet stuff. looks like a solution instead of using webview and css

    ReplyDelete
  4. Hi,

    Thanks for the tip. I am using an image which is bigger then the font im using but using the above code snippet is somehow aligning my image to the bottom edge of the text. So instead of my image extending below the line, its shifting the whole line downwards creating an extra gap between the paragraph lines.

    Any suggestions how i can achieve a top aligned Image span?

    ReplyDelete