How do I change the color of a widget at runtime?

I am trying to change the color of a widget using a different class. But I can't find the layout I'm trying to change because this layout is in a different XML file. The widget layout has a LinearLayout that uses shape.xml as the background. I've tried a lot of things but nothing worked.

Here's MyShape.xml:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid
android:color="#DDf5f5f5" />

<stroke
android:width="2dp"
android:color="#FFFFFFFF" />

<corners
android:bottomLeftRadius="7dp"
android:bottomRightRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp" />
</shape>

      

And this is what the class does when I click the Change Collor button:

public void onClick(View v) {

LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
LinearLayout myRoot = new LinearLayout(getApplicationContext());
View itemView = inflater.inflate(R.layout.widget_layout, myRoot);
LinearLayout linear = (LinearLayout) itemView.findViewById(R.id.layout);

GradientDrawable sd = (GradientDrawable) linear.getBackground().mutate();
sd.setColor(picker.getColor());
}

      

The WidgetColorPicker class uses the "widget_color.xml" layout, and the LinearLayout I want to change is in "widget_layout.xml".

+3


source to share





All Articles