Programmatically assign color to shape - android

I have a layout like this:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/user_color">
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
<item android:right="25dp">
<shape android:shape="rectangle">
<solid android:color="#color/user_background" />
</shape>
</item>
</layer-list>
How I'm calling the shape:
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/shape">
How can I programmatically change the color of the rectangle shape with id user_color?

int colorToPaint = getResources().getColor(android.R.color.white);// any color you want
Drawable tempDrawable = getResources().getDrawable(R.drawable.xml_layout);
LayerDrawable bubble = (LayerDrawable) tempDrawable; //cast to root element in xml
GradientDrawable solidColor = (GradientDrawable) bubble.findDrawableByLayerId(R.id.user_color);
solidColor.setColor(colorToPaint);

#user5262809
// add id to your linear layout
<LinearLayout
android:id="#+id/linearLayout"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/shape">
// then in code do this :
LinearLayout linearView = (LinearLayout) findViewById(R.id.linearLayout);
// added Anitha's code here
int colorToPaint = getResources().getColor(android.R.color.white);// any color you want
Drawable tempDrawable = getResources().getDrawable(R.drawable.xml_layout);
LayerDrawable bubble = (LayerDrawable) tempDrawable; //cast to root element in xml
GradientDrawable solidColor = (GradientDrawable) bubble.findDrawableByLayerId(R.id.user_color);
solidColor.setColor(colorToPaint);
// and then do this
linearView.setBackground(tempDrawable);
// hope this helps you :)

Try the below code:
GradientDrawable bgShape = (GradientDrawable)notesLayout.getBackground();
bgShape.setColor(Color.BLACK);

An Alternative to Anitha's answer would be-
If the LayerDrawable is already set to your ImageView use below code.
LinearLayout mLinearLayout = (LinearLayout)findViewById(R.id.my_linear_layout);
((LayerDrawable)mLinearLayout.getBackground()).findDrawableByLayerId(R.id.user_color).setColorFilter(getResources().getColor(R.color.white),PorterDuff.Mode.SRC_IN);
This way, if you already have a reference to your LinearLayout you do the whole color change in just a single line. And you don't even need to call setBackground() for the change to show!

Related

Background Colour Change At Run Time Android

I am Using LinearLayout to set BackGround Shape which has curve Corner. I have created drawable XML file. When I try to change LinearLayout backGround Colour at RunTime In My Activity, the colour appears is reflected in the Layout but background shape is not been applied. Need help on this
My layout.xml file:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/month_card"
android:backgroundTint="#drawable/circle_corner_rectangle"
app:backgroundTintMode="src_over">
shape.xml file
<shape android:shape="rectangle" >
<corners android:radius="500dip" />
<stroke android:width="2dip" android:color="#color/colorPrimary" />
<gradient android:angle="-90"/>
</shape>
Finally setting it on runtime inside the activity
layout.setBackgroundColor(colorList.get(position));
Use
final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.circle_corner_rectangle)
);
} else {
layout.setBackground(ContextCompat.getDrawable(context,R.drawable.circle_corner_rectangle));
}
instead of
layout.setBackgroundColor(colorList.get(position));
Try this code
circle_corner_rectangle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#E0F2F1" />
<corners android:radius="6dp"/>
</shape>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/month_card"
android:backgroundTint="#drawable/circle_corner_rectangle">
Maybe this work in your case
val shape = GradientDrawable()
shape.shape = GradientDrawable.RECTANGLE
shape.setStroke(mStrokeWidth!!,mStrokeColor!!)
shape.cornerRadius = 2f
imageView.background = shape
This code is in kotlin
Just try this ,,
layout.setBackgroundColor(Color.parseColor("#20A4E8"));
(or)
layout.setBackgroundColor(Color.BLUE);
just add another xml file You want and add this code in run time
layout.setBackgroundTintList(getContext.getResources().getColorStateList(R.color.your_xml_name));
Try this:
Drawable drawable = yourView.getBackground();
try {
drawable.setColorFilter(Color.parseColor(yourColor), PorterDuff.Mode.MULTIPLY);
} catch (Exception e) {
e.printStackTrace();
}

Animate layout's background color change

I have a RelativeLayout to which I have set a background from drawable.I was able to change the background of RelativeLayout to another when the RadioButton is checked. But how do I give an animation to it when it changes?
Code:
activity_main.xml:
<RelativeLayout
android:layout_width="80dp"
android:layout_height="50dp"
android:gravity="center"
android:background="#drawable/original"
android:id="#+id/rel1">
<RadioButton
android:id="#+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
original.xml(drawable):
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid
android:color="#ffffff">
</solid>
<corners
android:radius="50dp">
</corners>
</shape>
pressed.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid
android:color="#2196F3">
</solid>
<corners
android:radius="50dp">
</corners>
</shape>
Java Class:
radio.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
relativeLayout.setBackgroundResource(R.drawable.pressed);
}
}
});
The problem boils down to having somehow clipped corners and animating the layout background. So, in theory, we can set a foreground drawable to the layout and animate background drawable using ArgbEvaluator.
Moving to practice.
Take a look at this answer, where the author shares a mask drawable, which can be handy for your problem:
Apply that drawable as a foreground of your layout:
<RelativeLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="300dp"
android:foreground="#drawable/frame"
android:background="#color/colorAccent" />
In the code, whenever needed to perform animation:
final int from = ContextCompat.getColor(this, R.color.colorAccent);
final int to = ContextCompat.getColor(this, R.color.colorPrimary);
ValueAnimator anim = new ValueAnimator();
anim.setIntValues(from, to);
anim.setEvaluator(new ArgbEvaluator());
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
view.setBackgroundColor((Integer)valueAnimator.getAnimatedValue());
}
});
anim.setDuration(1000);
anim.start();
Here's what you'll get on output:
If you want to change frame drawable's color, you can wrap it into an xml and apply android:tint.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item >
<bitmap android:src="#drawable/frame" android:tint="#ccaaff"/>
</item>
</layer-list>
Now set this drawable as the foreground of your layout.
The same effect can be achieved entirely in Code
Create Background with Corner of Rectangle Programmatically
//Background
backgroundDrawable = GradientDrawable()
backgroundDrawable.cornerRadius = rectangleCornerRadius
backgroundDrawable.shape = GradientDrawable.RECTANGLE
backgroundDrawable.setColor(rectangleColor)
background = backgroundDrawable
Animate Color Change
val objectAnimator = ObjectAnimator.ofObject(backgroundDrawable, "color",
ArgbEvaluator(),
Color.parseColor("#FFFFFFFF"),
Color.parseColor("#FF78c5f9"))
objectAnimator .setDuration(1000);
objectAnimator .start();

can't get reference to item inside of layer-list

I want to get a reference to item inside of the layer-list for changing some attributes programmatically, But I can't see any difference and seems it does not work.
this is my code:
logo.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/circle">
<shape android:shape="oval">
<solid android:color="#fff"/>
<size android:height="33px" android:width="33px"/>
<stroke android:color="#000" android:width="2px"/>
</shape>
</item>
</layer-list>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.shahin.testing2.MainActivity">
<Button
android:layout_width="33px"
android:id="#+id/button"
android:layout_height="33px"
android:background="#drawable/logo"/>
</LinearLayout>
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayerDrawable layerDrawable = (LayerDrawable)
ContextCompat.getDrawable(getApplicationContext(),R.drawable.logo);
GradientDrawable gradientDrawable = (GradientDrawable)
layerDrawable.findDrawableByLayerId(R.id.circle);
gradientDrawable.setStroke(10, Color.BLUE);
Button button = (Button)findViewById(R.id.button);
button.setBackgroundResource(R.drawable.logo);
}
in this case, when I changed the stroke color and width, no difference has appeared, what is the problem?

Get a textView background color with ShapeDrawable

I have a textview with the background defined in a xml file.
<TextView
android:id="#+id/event_tvColor"
android:layout_width="40dip"
android:layout_height="40dip"
android:text=" "
android:background="#drawable/et_style_color_service_edit"
android:clickable="true"
/>
xml file : et_style_color_service_edit.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#color/eventColor"/>
<stroke android:width="0sp" android:color="#FFFFFF" />
<size android:width="20dp"
android:height="20dp"/>
</shape>
And i need to get the color that the view have in a one time.
ShapeDrawable sc = (ShapeDrawable)tvColor.getBackground();
...............
Note that i need to use ShapeDrawable and not GradientDrawable.
Thank you for your help and time.
Solution........
Solution The xml loads into the app as a gradientdrawable and not as a shapedrawable. We have to define the shapeDrawable in java
ShapeDrawable sd = new ShapeDrawable(new RectShape);
sd.getPaint().setColor(0xFF0000FF);
if anyone have a better solution can tell.
After further research, there currently is no way of getting the xml loaded ShapeDrawable's color. What you have to do is just track your color changes so you know what color you are setting it to, ie:
int currentColor = Color.WHITE; //this is the default color (color set in xml)
public void changeColor() {
if (currentColor == Color.WHITE) {
currentColor = Color.BLUE;
} else {
currentColor = Color.WHITE;
}
GradientDrawable gd = (GradientDrawable)tvColor.getBackground();
gd.setColor(currentColor);
}

How to change color of drawable shapes in android

I am developing small android application in which I set drawable resource as background for linear layout. Now what I want to do change background color of linear layout dynamically, but within drawable resource.
My code looks like :
// bcd.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:endColor="#22000000"
android:startColor="#22000000"
android:angle="270" />
<stroke
android:width="3dp"
android:color="#color/white" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<LinearLayout
android:id="#+id/lin_llt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
and I set background for linear layout in my activity like this...
parentLayout = (LinearLayout) view.findViewById(R.id.lin_llt);
parentLayout.setBackgroundResource(R.drawable.bcd);
Now what I want to do i want to change color of my drawable resource that mean change color of my linear layout with rounded corner and padding define in drawable..
I tried this in following way
ShapeDrawable bgShape = (ShapeDrawable )parentLayout.getBackground();
bgShape.getPaint().setColor(Color.BLACK);
but its not working for me. any other solution .
So how to do it...
Need help...
thank you...
Change the layout color dynamically
LinearLayout Layout = (LinearLayout) findViewById(R.layout.id);
Layout.setBackgroundColor(Color.parseColor("#ffffff"));
Dynamically set the background color gradient
View layout = findViewById(R.id.mainlayout);
GradientDrawable gd = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
new int[] {0xFF616261,0xFF131313});
gd.setCornerRadius(0f);
layout.setBackgroundDrawable(gd);
You could try something like this :
Drawable sampleDrawable = context.getResources().getDrawable(R.drawable.balloons);
sampleDrawable.setColorFilter(new PorterDuffColorFilter(0xffff00,PorterDuff.Mode.MULTIPLY));
and for more you could refer to :
How to change colors of a Drawable in Android?
Change drawable color programmatically
Android: Change Shape Color in runtime
http://pastebin.com/Hd2aU4XC
You could also try this :
private static final int[] FROM_COLOR = new int[]{49, 179, 110};
private static final int THRESHOLD = 3;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test_colors);
ImageView iv = (ImageView) findViewById(R.id.img);
Drawable d = getResources().getDrawable(RES);
iv.setImageDrawable(adjust(d));
}
private Drawable adjust(Drawable d)
{
int to = Color.RED;
//Need to copy to ensure that the bitmap is mutable.
Bitmap src = ((BitmapDrawable) d).getBitmap();
Bitmap bitmap = src.copy(Bitmap.Config.ARGB_8888, true);
for(int x = 0;x < bitmap.getWidth();x++)
for(int y = 0;y < bitmap.getHeight();y++)
if(match(bitmap.getPixel(x, y)))
bitmap.setPixel(x, y, to);
return new BitmapDrawable(bitmap);
}
private boolean match(int pixel)
{
//There may be a better way to match, but I wanted to do a comparison ignoring
//transparency, so I couldn't just do a direct integer compare.
return Math.abs(Color.red(pixel) - FROM_COLOR[0]) < THRESHOLD && Math.abs(Color.green(pixel) - FROM_COLOR[1]) < THRESHOLD && Math.abs(Color.blue(pixel) - FROM_COLOR[2]) < THRESHOLD;
}
as given in How to change colors of a Drawable in Android?
The following works great for setting the color of the drawable programmatically without changing its shape:
parentLayout.getBackground().setColorFilter(
Color.BLACK,
PorterDuff.Mode.SRC_ATOP
);
use this..
<solid android:color="#e1e1e1" />
<stroke
android:width="2dp"
android:color="#808080" />
<corners android:radius="10dp" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
Also possible way is to use:
val layerDrawable : LayerDrawable = imageView.background as LayerDrawable
val bgShape = layerDrawable.findDrawableByLayerId(R.id.shape_id) as GradientDrawable
bgShape.setColor(ContextCompat.getColor(context, R.color.colorPrimary))
with example (drawable/circle.xml):
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/shape_id">
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="1000dp" />
<solid android:color="#F4B528" />
<padding
android:bottom="4dp"
android:left="4dp"
android:right="4dp"
android:top="4dp" />
</shape>
</item>
</layer-list>
and ImageView:
<ImageView
android:id="#+id/imageView"
android:layout_width="16dp"
android:layout_height="16dp"
android:background="#drawable/circle"
/>
One approach would be to create a second drawable XML with the 2nd color and then change the background of the layout with the 2nd drawable.

Categories

Resources