How to align TextView around an ImageView?

Debopam Mitra picture Debopam Mitra · Jul 15, 2012 · Viewed 8.6k times · Source

enter image description here

I am trying to align the TextView around ImageView. I am using the following code:

 private void createSpannableText(){
        TextView myTextView = (TextView) findViewById(R.id.textView);
        SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.append(this.getText(R.string.loren__ipsum__max));
        int lengthOfPart1 = builder.length();
        builder.append(" ");
        builder.append(this.getText(R.string.lorem__ipsum));
        Drawable d = getResources().getDrawable(R.drawable.myImage);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); // <---- Very important otherwise your image won't appear
        ImageSpan myImage = new ImageSpan(d);
        builder.setSpan(myImage, 0, lengthOfPart1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        myTextView.setText(builder);
    }

But couldn't get the exact result. What shall I do? Do I need to use SpannableStringBuilder in this case or there is another way. Please help. I used this post-http://majaxandroidtips.blogspot.in/2009/06/how-to-have-few-layout-elements-wrap_17.html to have the solution.

P.S.: I also want 6dp margin around the ImageView

Answer

K_Anas picture K_Anas · Jul 15, 2012

You can achieve this by using the android.text.style.LeadingMarginSpan.LeadingMarginSpan2 interface which is available in API 8. Here is the article, not in English though, translate it using your browser. Besides you can download the source code of the example directly from here.

Your layout:

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dp">
    <TextView
        android:textSize="18.0sp"
        android:id="@+id/message_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/text" />
    <ImageView
        android:src="@drawable/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/icon" />
</RelativeLayout>

Helper class implements LeadingMarginSpan.LeadingMarginSpan2

class MyLeadingMarginSpan2 implements LeadingMarginSpan.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) {
            /*
             * Данный отступ будет применен к количеству строк
             * возвращаемых getLeadingMarginLineCount()
             */
            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) {}

    /*
     * Возвращает количество строк, к которым должен быть 
     * применен отступ возвращаемый методом getLeadingMargin(true)
     * Замечание:
     * Отступ применяется только к N строкам первого параграфа.
     */
    @Override
    public int getLeadingMarginLineCount() {
        return lines;
    }
};

Your activity code:

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String text = getString(R.string.text);

        // Получаем иконку и ее ширину
        Drawable dIcon = getResources().getDrawable(R.drawable.icon);
        int leftMargin = dIcon.getIntrinsicWidth() + 10;

        // Устанавливаем иконку в R.id.icon
        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);
    }

And finally here a demo result:

enter image description here