代码之家  ›  专栏  ›  技术社区  ›  Elad Benda

在compoundTextView中将图像居中,会向下移动文本

  •  0
  • Elad Benda  · 技术社区  · 7 年前

    我想把它动态地添加到文本视图中。

    我有3个文本视图,根据某种状态,我添加它作为一个compoundDrawable。

    TextViewCompat.setCompoundDrawablesRelative(targetTextView, null, null, drawable, null);
    

    我希望图像几乎垂直居中于文本视图+比中心低1sp的长度。所以在每个文本视图中我都添加了

          android:gravity="center_vertical"
    

    但是在添加compundimageview之前,文本视图似乎也相对于它的位置向下移动了。

    enter image description here

    enter image description here

    但是等待observerTree会让代码变得很复杂。

    以下是我对(1)选项的代码:

      private void tintAndAddPadding(
    
    ...
    
    
          @DrawableRes int drawableId, @ColorRes int colorId) {
        Drawable drawable =
            Preconditions.checkNotNull(AppCompatResources.getDrawable(getContext(), drawableId));
        Drawable drawableWithTint = DrawableCompat.wrap(drawable);
        DrawableCompat.setTint(
            drawableWithTint.mutate(), getContext().getResources().getColor(colorId));
        // Bitmap dimensions sets the canvas dimensions
        Bitmap bitmap =
            Bitmap.createBitmap(
                getContext()
                    .getResources()
                    .getDimensionPixelSize(R.dimen.account_menu_collapse_expand_width),
                getContext()
                    .getResources()
                    .getDimensionPixelSize(R.dimen.account_menu_collapse_expand_canvas_height),
                Bitmap.Config.ARGB_8888);
    
        Canvas canvas = new Canvas(bitmap);
    
        // Drawable bounds should be all 4 coordinates on the canvas to draw on.
        // This implies the drawable width and height.
        drawableWithTint.setBounds(
            0,
            getContext()
                .getResources()
                .getDimensionPixelSize(R.dimen.account_menu_collapse_expand_top_padding)
            , canvas.getWidth(),
            canvas.getHeight() -
                getContext()
                    .getResources()
                    .getDimensionPixelSize(R.dimen.account_menu_collapse_expand_top_padding));
        drawableWithTint.draw(canvas);
    
       TextViewCompat.setCompoundDrawablesRelative(targetTextView, null, null, drawableWithTint, null);
        // Padding between text and drawable
        targetTextView.setCompoundDrawablePadding(
            getContext()
                .getResources()
                .getDimensionPixelSize(R.dimen.account_menu_collapse_expand_left_padding))
      }
    
    0 回复  |  直到 7 年前