android - 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>
如果我将“主色”中的纯色更改为透明,整个背景将使用“下划线颜色”设置。
解决方案
如果覆盖渐变层的层的颜色不透明,则用于在视图底部创建一条线的技术有效。您正在尝试做的是应用替换(擦除)底层渐变的透明层。这不是它的工作原理:透明的叠加层保留了底层颜色,这里是渐变,未触及。
这是可用于 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
文档中提到了它。
推荐阅读
- r - 试图在 R 中传播数据帧
- angularjs - 从导入的模型中调用时,createInput() 的行为不符合预期
- r - 使用 zoo 对象创建多个滞后变量
- maven - mvn verify sonar:sonar 命令是否将代码推送到声纳 Web 仪表板?
- autohotkey - 使用 AutoHotKey 暂时禁用卡住的修饰键
- javascript - 如何在 TypeScript 中使用无 typescript React 组件?
- javascript - node-vibrant 最小颜色
- python - Firebase 规则 - 即使“获取”请求有效(REST),orderBy 查询中的权限也被拒绝
- mysql - 如果值没有改变,SQL 触发器更新记录而不是插入
- c# - 当需要设计模块化架构时,对象铸造是现实的必然吗?