Dynamically changing the background color in Android Widgets at runtime

This is something we’d struggled with for a while. The older versions of Clarus Battery and Signal used multiple layout files, with one for each color. This however does not allow the user to choose their own background.

The quick and dirty way of dynamically changing the background color for a widget is as follows:

  • Create a Bitmap
  • Load the Bitmap to the Canvas
  • Set color to the Canvas
  • Use RemoteViews. setImageViewBitmap() method to set the Bitmap to the ImageView

Sample code:

Layout file

<?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout
       xmlns:android="http://schemas.android.com/apk/res/android "
       android:layout_width="fill_parent"
       android:layout_height="fill_parent">

           <ImageView
                 xmlns:android="http://schemas.android.com/apk/res/android "
                 android:layout_width="fill_parent"
                 android:layout_height="fill_parent"
                 android:id="@+id/bgcolor"
                 android:scaleType="fitXY"
                  />

           <LinearLayout
                 xmlns:android="http://schemas.android.com/apk/res/android "
                 android:orientation="horizontal"
                 android:layout_width="fill_parent"
                 android:layout_height="fill_parent"
                 android:layout_gravity="center_horizontal|center_vertical"
                 android:gravity="center_horizontal|center_vertical"
                 android:id="@+id/mainlayout"
                 android:layout_marginTop="10dip">

                <TextView
                       android:layout_width="fill_parent"
                       android:layout_height="fill_parent"
                       android:text="Change Background!!!"
                       android:textSize="15dip"
                       android:layout_gravity="center_horizontal"
                       android:gravity="center_horizontal|center_vertical"
                       android:visibility="visible" />
           </LinearLayout>
  </RelativeLayout>



Creating the bitmap

    public static Bitmap getBackground (int bgcolor)
    {
	try
        {
			Bitmap.Config config = Bitmap.Config.ARGB_8888; // Bitmap.Config.ARGB_8888 Bitmap.Config.ARGB_4444 to be used as these two config constant supports transparency
            Bitmap bitmap = Bitmap.createBitmap(2, 2, config); // Create a Bitmap

            Canvas canvas =  new Canvas(bitmap); // Load the Bitmap to the Canvas
            canvas.drawColor(bgcolor); //Set the color

            return bitmap;
        }
        catch (Exception e)
        {
			return null;
        }
	}



Set the Bitmap to the ImageView

        remoteViews.setImageViewBitmap(R.id.bgcolor, getBackground(bgcolor));

1 Comment

  1. by Manjiri on November 25, 2014  10:07 pm Reply

    It is not working....

Leave a reply

Your email address will not be published.