1

I would like to set a background drawable (or resource) on a TextView, not taking into account its compound drawable width (and paddings).

Getting the width of the compound (left one to be more precise), and its paddings should not be a problem, but the setting of the background on the width of the textview minus the width of the compound drawable (described above).

Should you have any advice on doing that, please let me know.

Here's the needed result: separator

PS. I thought about having a horizontal LinearLayout with an ImageView and TextView as its children, and having the background set on the textview only, but I am interested in having the same result with less Views (in this case, exactly one), if it is possible.

4

1 回答 1

2

您可以使用支持插图的LayerDrawable,例如:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:left="dimension" android:right="dimension">
        <shape android:shape="rectangle">
            <solid android:color="color" />
        </shape>
    </item>
</layer-list>

如果你想动态地改变你的 Drawable 你最好写你自己的 Drawable 类。例如,以下 DividerDrawable 将一条线绘制到白色背景上的给定填充:

public class DividerDrawable extends Drawable {

    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private float mDensity;
    private int mPaddingLeft = 0;

    public DividerDrawable(Context context) {
        mPaint.setColor(Color.BLACK);
        mDensity = context.getResources().getDisplayMetrics().density;
    }

    @Override
    public void draw(Canvas canvas) {
        int width = canvas.getWidth();
        int height = canvas.getHeight();
        canvas.drawColor(Color.WHITE);
        canvas.drawRect(mPaddingLeft, height - mDensity, width, height, mPaint);
    }

    @Override
    public void setAlpha(int alpha) {

    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {

    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    public void setPaddingLeft(int paddingLeft) {
        if (mPaddingLeft != paddingLeft) {
            mPaddingLeft = paddingLeft;
            invalidateSelf();
        }
    }
}

要根据您的左侧 CompoundDrawable 设置左侧填充,您可以执行以下操作:

private void setBackground(TextView textView, DividerDrawable background) {
    Drawable drawableLeft = textView.getCompoundDrawables()[0];
    int paddingLeft = drawableLeft != null ?
            textView.getPaddingLeft() + drawableLeft.getIntrinsicWidth() + textView.getCompoundDrawablePadding() :
            textView.getPaddingLeft();
    background.setPaddingLeft(paddingLeft);
    textView.setBackground(background);
}

为了充分利用所有这些调用它像这样:

    DividerDrawable dividerDrawable = new DividerDrawable(this);
    TextView textView = (TextView) findViewById(R.id.text);
    setBackground(textView, dividerDrawable);
于 2015-12-21T15:18:27.060 回答