答案 0 :(得分:5)
通过xml执行:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:right="100dp">
<shape android:shape="rectangle">
<size android:height="100dp" android:width="100dp"/>
<solid android:color="@android:color/black"/>
</shape>
</item>
<item android:left="100dp">
<shape android:shape="rectangle">
<size android:height="100dp" android:width="100dp"/>
<solid android:color="@android:color/holo_green_light"/>
</shape>
</item>
</layer-list>
将其放入res/drawable
文件夹并指定为android:background
到图像
答案 1 :(得分:0)
您可以尝试创建2个具有相应颜色的形状,然后使用它们。
您可以通过为它们创建尺寸和颜色来制作这些形状。
答案 2 :(得分:0)
有可能。你可以:
1)创建一个形状
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke
android:width="1dp"
android:color="@color/gray_light" />
<gradient
android:type="linear"
android:centerX="0"
android:centerY="1"
android:startColor="#bff54a"
android:endColor="#88c010" />
<corners
android:bottomLeftRadius="8dp"
android:bottomRightRadius="8dp"
android:topLeftRadius="8dp"
android:topRightRadius="8dp" />
</shape>
2)扩展drawable类
public class ColorBarDrawable extends Drawable {
private int[] themeColors;
public ColorBarDrawable(int[] themeColors) {
this.themeColors = themeColors;
}
@Override
public void draw(Canvas canvas) {
// get drawable dimensions
Rect bounds = getBounds();
int width = bounds.right - bounds.left;
int height = bounds.bottom - bounds.top;
// draw background gradient
Paint backgroundPaint = new Paint();
int barWidth = width / themeColors.length;
int barWidthRemainder = width % themeColors.length;
for (int i = 0; i < themeColors.length; i++) {
backgroundPaint.setColor(themeColors[i]);
canvas.drawRect(i * barWidth, 0, (i + 1) * barWidth, height, backgroundPaint);
}
// draw remainder, if exists
if (barWidthRemainder > 0) {
canvas.drawRect(themeColors.length * barWidth, 0, themeColors.length * barWidth + barWidthRemainder, height, backgroundPaint);
}
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
@Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
}
来源:手写代码 - StackOverflow