Jak wyrównać widok tekstu wokół widoku ImageView?

Tutaj wpisz opis obrazka

Próbuję wyrównać widok tekstu wokół ImageView. Używam następującego kodu:

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

Ale nie udało się uzyskać dokładnego wyniku. Co mam zrobić? Czy muszę używać SpannableStringBuilder w tym przypadku, czy jest inny sposób. Proszę o pomoc. Użyłem tego post-http://majaxandroidtips.blogspot.in/2009/06/how-to-have-few-layout-elements-wrap_17.html aby mieć rozwiązanie.

P. S.: ja też chcę 6DP marginesu wokół ImageView

Author: Debopam Mitra, 2012-07-15

1 answers

Można to osiągnąć za pomocą interfejsu android.text.style.LeadingMarginSpan.LeadingMarginSpan2 dostępnego w API 8. Oto Artykuł , ale nie w języku angielskim, przetłumacz go za pomocą przeglądarki. Poza tym możesz pobrać kod źródłowy przykładu bezpośrednio z tutaj .

Twój układ:

<?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>

Implementacje klasy Helper 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;
    }
};

Twój kod aktywności:

 @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);
    }

I na koniec wynik demo:

Tutaj wpisz opis obrazka

 17
Author: K_Anas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-15 17:58:10