gpt4 book ai didi

android - 在 TextView 上绘制背景(不是全宽)

转载 作者:行者123 更新时间:2023-11-30 01:41:50 26 4
gpt4 key购买 nike

我想在 TextView 上设置背景可绘制对象(或资源),而不考虑其复合可绘制对象宽度(和填充)。

获取复合的宽度(更精确的是留一个),它的paddings应该没有问题,但是在textview的宽度上设置背景减去复合drawable的宽度(上面有描述) .

如果您对此有任何建议,请告诉我。

这是所需的结果: separator

附言。我想过有一个水平的 LinearLayout 和一个 ImageView 和 TextView 作为它的 child ,并且只在 textview 上设置背景,但我有兴趣用更少的 View (在这种情况下,正好是一个)获得相同的结果,如果它是可能。

最佳答案

你可以使用 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);

关于android - 在 TextView 上绘制背景(不是全宽),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34398269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com