首页 > 解决方案 > Android Layout 透明布局背景带下划线

问题描述

我正在尝试绘制一个可绘制的布局背景,它只是具有 1-2 dp 高度的渐变下划线,其余部分是透明的,因此上部将具有父背景。

这就是我所拥有的。

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android>

<!-- underline color -->
<item>
    <shape>
        <gradient
            android:startColor="@color/colorPrimaryDark"
            android:endColor="#FFFFFFFF"
            android:centerY="0.5"
            android:angle="0"/>


    </shape>
</item>


<!-- main color -->
<item android:bottom="2.5dp">
    <shape android:shape="rectangle">
        <solid android:color="@color/white" />
        <padding
            android:top="4dp"
            android:bottom="4dp" />
    </shape>
</item>

如果我将“主色”中的纯色更改为透明,整个背景将使用“下划线颜色”设置。

标签: androidandroid-layout

解决方案


如果覆盖渐变层的层的颜色不透明,则用于在视图底部创建一条线的技术有效。您正在尝试做的是应用替换(擦除)底层渐变的透明层。这不是它的工作原理:透明的叠加层保留了底层颜色,这里是渐变,未触及。

这是可用于 API 23+ 的备用图层列表可绘制对象:

underline_drawable.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:gravity="bottom">
        <shape>
            <size android:height="2dp" />
            <gradient
                android:angle="0"
                android:centerY="0.5"
                android:endColor="#FFFFFFFF"
                android:startColor="@color/colorPrimaryDark" />
        </shape>
    </item>
</layer-list>

这是它的样子:

在此处输入图像描述

在 API 23 之前,您可以使用以下自定义可绘制对象,但必须在代码中进行设置。

GradientUnderline.java

public class GradientUnderline extends Drawable {
    private Shader mShader;
    private final Paint mPaint;
    private int mHeight = -1;
    private int mStartColor = Color.BLACK;
    private int mEndColor = Color.WHITE;
    private int mLastWidth;

    public GradientUnderline() {
        mPaint = new Paint();
    }

    public GradientUnderline(int lineHeight, int startColor, int endColor) {
        mPaint = new Paint();
        mHeight = lineHeight;
        mStartColor = startColor;
        mEndColor = endColor;
    }

    @Override
    public void draw(@NonNull Canvas canvas) {
        if (mShader == null || getBounds().width() != mLastWidth) {
            mLastWidth = getBounds().width();
            mShader = new LinearGradient(0, 0, getBounds().width(), mHeight, mStartColor,
                                         mEndColor, Shader.TileMode.CLAMP);
            mPaint.setShader(mShader);
        }
        canvas.drawRect(0, getBounds().height() - mHeight, getBounds().width(),
                        getBounds().height(), mPaint);
    }

    @Override
    public void setAlpha(int alpha) {

    }

    @Override
    public void setColorFilter(@Nullable ColorFilter colorFilter) {

    }

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

我错过了android:gravity最初的可用性,因为“可绘制资源”页面上没有提到它。但是,在LayerDrawable文档中提到了它。


推荐阅读