我想在TextView上设置背景可绘制(或资源),而不考虑其复合可绘制宽度(和填充)。
获取化合物的宽度(左边一个更精确),它的填充应该不是问题,但是textview宽度的背景设置减去复合drawable的宽度(如上所述)
如果您对此有任何建议,请告诉我。
PS。我想过一个水平的LinearLayout,它有一个ImageView和TextView作为它的子节点,并且只在textview上设置了背景,但是我有兴趣用较少的视图(在这种情况下,恰好是一个)获得相同的结果,如果它是可能的。
答案 0 :(得分:1)
您可以使用支持插入的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);