Change color of one LinearLayout to two colors by using canvas

87 Views Asked by At

I'm trying to change background color of one LinearLayout to two colors for some reasons like the following pic:

two colors

I'm writing this code but the problem this LinearLayout take third different color for the two parts like this pic:

one color

What is the problem in the logic of my code I don't know or I can not do something like that in Android?

Code:

c = (LinearLayout) findViewById(R.id.cell);
c.setBackgroundColor(getColor(container.get(0)));
c.setBackgroundColor(getColor(container.get(1)));
int width = c.getWidth(), height = c.getHeight();
if (width == 0 || height == 0) {
    width = 100;
    height = 100;
}
Bitmap bitmap;
try {

    bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
} catch (Exception e) {
    e.printStackTrace();
    return;
}

Canvas canvas = new Canvas(bitmap);

Path path = new Path();
path.moveTo(0, height);
path.lineTo(0, 0);
path.lineTo(width, 0);
path.lineTo(0, height);
path.close();

Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setColor(getColor(container.get(0)));
canvas.drawPath(path, paint);

path = new Path();
path.moveTo(width, 0);
path.lineTo(width, height);
path.lineTo(0, height);
path.lineTo(width, 0);
path.close();

paint = new Paint();
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setColor(getColor(container.get(1)));
canvas.drawPath(path, paint);
1

There are 1 best solutions below

0
On

I solved my problem, the problem was in the way of parsing color in setColor method I replaced this one:

paint.setColor(getColor(container.get(1)));

by:

paint.setColor(ResourcesCompat.getColor(getResources(),getColor(container.get(1)), null));

and everything is ok now.