Uisng XML is it possible to create a drawable where half of it would be color1 and another half would be color2? When I set that drawable as a background of a view it should look like in the image below.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Doing it by 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>
Put it in res/drawable
folder and assign as android:background
to image
回答2:
You can try by creating 2 shapes with respective colors and then use them.
You can make these shapes by writing xml for them giving the dimensions and colors.
回答3:
It is possible. You can :
1) Create a shape
<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) Extends the drawable class
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;
}
}
Source : Chiral Code - StackOverflow