Cannot Set Image and Text in Center Vertical Andro

2019-08-14 04:37发布

问题:

I got problem when I try to set image and text vertically center. So I'm using SpannableStringBuilder and ImageSpan. I try to combile image and text by this code :

@Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            Drawable drawableIcon = null;

            // space added before text for convenience
            SpannableStringBuilder sb = new SpannableStringBuilder(" ");

            ImageSpan span = null;
            switch (position) {
                case 0:
                    drawableIcon = getResources().getDrawable(R.drawable.ic_action_unread);
                    drawableIcon.setBounds(0, 0, drawableIcon.getIntrinsicWidth(), drawableIcon.getIntrinsicHeight());
                    span = new ImageSpan(drawableIcon, ImageSpan.ALIGN_BASELINE);
                    sb.append(getString(R.string.title_task_fragment).toUpperCase(l));
                    sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                    //return getString(R.string.title_task_fragment).toUpperCase(l);
                    return sb;
                case 1:
                    drawableIcon = getResources().getDrawable(R.drawable.ic_action_camera);
                    drawableIcon.setBounds(0, 0, drawableIcon.getIntrinsicWidth(), drawableIcon.getIntrinsicHeight());
                    span = new ImageSpan(drawableIcon, ImageSpan.ALIGN_BASELINE);
                    sb.append(getString(R.string.title_news_fragment).toUpperCase(l));
                    sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                    //return getString(R.string.title_news_fragment).toUpperCase(l);
                    return sb;
                case 2:
                    drawableIcon = getResources().getDrawable(R.drawable.ic_action_settings_white);
                    drawableIcon.setBounds(0, 0, drawableIcon.getIntrinsicWidth(), drawableIcon.getIntrinsicHeight());
                    span = new ImageSpan(drawableIcon, ImageSpan.ALIGN_BASELINE);
                    sb.append(getString(R.string.title_settings_fragment).toUpperCase(l));
                    sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                    //return getString(R.string.title_settings_fragment).toUpperCase(l);
                    return sb;
            }
            return null;
        }

And this is my xml layout which contains PagerTabStrip

<android.support.v4.view.ViewPager android:id="@+id/container"
        android:layout_width="match_parent" android:layout_height="match_parent"
        tools:context=".WrapperMainActivity" >
        <android.support.v4.view.PagerTabStrip
            android:id="@+id/pager_tab_strip"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="@color/title_strip_background1"
            android:textColor="#fff" />
    </android.support.v4.view.ViewPager>

I've already set the ImageSpan.ALIGN_BASELINE, but I'm not get the expected result. The text remains at the bottom, not aligned in the same line of the image icon...

Have I missed something?

Thanks...

回答1:

PagerTabStrip:
Height - 48dp Padding - 12dp left and right of text, 20dp from bottom for a single line of text, 12dp from bottom for two lines of text

In my case I did it for one line text

<android.support.v4.view.PagerTabStrip
        android:id="@+id/pager_title_strip"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_gravity="top"
        android:paddingBottom="20dp"
        android:textColor="#ffffff" />


回答2:

This solution should work. I have tested it and am using it for sometime. It doesn't consider the ascent and decent but it Aligns the drawable in the center. This solution is

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.text.style.ImageSpan;

import java.lang.ref.WeakReference;

public class CustomImageSpan extends ImageSpan {

  /**
   * A constant indicating that the center of this span should be aligned
   * with the center of the surrounding text
   */
  public static final int ALIGN_CENTER = -12;
  private WeakReference<Drawable> mDrawable;
  private int mAlignment;

  public CustomImageSpan(Context context, final int drawableRes, int alignment) {
    super(context, drawableRes);
    mAlignment = alignment;
  }

  @Override
  public int getSize(Paint paint, CharSequence text,
                     int start, int end,
                     Paint.FontMetricsInt fm) {
    Drawable d = getCachedDrawable();
    Rect rect = d.getBounds();
    if (fm != null) {
      Paint.FontMetricsInt pfm = paint.getFontMetricsInt();
      fm.ascent = pfm.ascent;
      fm.descent = pfm.descent;
      fm.top = pfm.top;
      fm.bottom = pfm.bottom;
    }
    return rect.right;
  }

  @Override
  public void draw(@NonNull Canvas canvas, CharSequence text,
                   int start, int end, float x,
                   int top, int y, int bottom, @NonNull Paint paint) {
    if (mAlignment == ALIGN_CENTER) {
      Drawable cachedDrawable = getCachedDrawable();
      canvas.save();
      //Get the center point and set the Y coordinate considering the drawable height for aligning the icon vertically
      int transY = ((top + bottom) / 2) - cachedDrawable.getIntrinsicHeight() / 2;
      canvas.translate(x, transY);
      cachedDrawable.draw(canvas);
      canvas.restore();
    } else {
      super.draw(canvas, text, start, end, x, top, y , bottom, paint);
    }
  }

  // Redefined locally because it is a private member from DynamicDrawableSpan
  private Drawable getCachedDrawable() {
    WeakReference<Drawable> wr = mDrawable;
    Drawable d = null;
    if (wr != null) {
      d = wr.get();
    }
    if (d == null) {
      d = getDrawable();
      mDrawable = new WeakReference<>(d);
    }
    return d;
  }
}