Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android AppWidget TextView: How to set background color at run time

Tags:

android

I am trying to create an AppWidget, in which the background color of a TextView changes at random at specified periodic interval.

The TextView is defined in layout xml file as

<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/widget"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <TextView  
        android:id="@+id/message"
        android:background="#ff99ff"
        android:text="Hello Widget" />
</LinearLayout>

In update method, i have loaded the layout as

RemoteViews remoteView=new RemoteViews(context.getPackageName(),R.layout.widget_message);

To change the background of TextView i used the following statement

remoteView.setInt(R.id.message, "setBackgroundResource", R.color.col_1);

But i am getting a widget saying problem loading widget. If i remove the above line everything works fine.

LogCat says:

updateAppWidget couldn't find any view, using error view

android.widget.RemoteViews$ActionException: view: android.widget.TextView can't use method with RemoteViews: setBackgroundResource(int)

like image 627
Amit Avatar asked Mar 16 '10 10:03

Amit


2 Answers

Try this it will work fine.

remoteView.setInt(R.id.message, "setBackgroundColor", 
        android.graphics.Color.BLACK);
like image 93
Abhishek Jain Avatar answered Nov 10 '22 13:11

Abhishek Jain


If you have some shape as the background of the textview, where the background is defined in some drawable resource, then you can use

remoteViews.setInt(R.id.change,"setBackgroundResource", R.drawable.my_drawable_new);

In above code statement, R.id.change is the TextView with some background resource and you have defined some resources (my_drawable and my drawable_new) in your drawable folder.

<TextView
    android:id="@+id/change"
    android:background="@drawable/my_drawable">
</TextView
like image 9
T.M Avatar answered Nov 10 '22 12:11

T.M