Android应用小部件TextView:如何在运行时设置背景颜色

28

我正在尝试创建一个AppWidget,在其中TextView的背景颜色随机更改,并在指定的周期间隔内进行更改。

TextView在布局xml文件中定义为

<?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>

在update方法中,我已经加载了布局:

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

为了改变TextView的背景,我使用了以下语句

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

但我得到一个小部件,显示“问题加载小部件”。如果我删除上面的那一行,一切都正常。

LogCat显示:

updateAppWidget找不到任何视图, 使用错误视图

android.widget.RemoteViews$ActionException: 视图:android.widget.TextView无法 使用RemoteViews的方法: setBackgroundResource(int)

9个回答

68

试试这个,它会很好地工作。

remoteView.setInt(R.id.message, "setBackgroundColor", 
        android.graphics.Color.BLACK);

如果我想保留可绘制内容呢? - TheOnlyAnil
1
不适用于像LinearLayout这样的ViewGroup,但适用于像TextView这样的View。 - JoachimR

9
如果您在textview的背景中使用了某种形状,而该背景是在一些可绘制的资源中定义的,则可以使用以下方法:
remoteViews.setInt(R.id.change,"setBackgroundResource", R.drawable.my_drawable_new);

在上面的代码语句中,R.id.change是带有一些背景资源的TextView,您已经在drawable文件夹中定义了一些资源(my_drawable和my_drawable_new)。
<TextView
    android:id="@+id/change"
    android:background="@drawable/my_drawable">
</TextView

7
如果您想设置文本本身的颜色,请使用:
remoteViews.setInt(R.id.tvAmountThisYear, "setTextColor",
                android.graphics.Color.RED);

6

contentView.setInt(R.id.tv_contactText, "setBackgroundColor", Color.parseColor(hexColor));

可以翻译为:使用hexColor参数解析颜色值,并将其设置为id为tv_contactText的视图的背景颜色。

1

从Android 2.2开始,可以调用此方法,之前不行。


1
Tomas是正确的。我的解决方案是创建两个视图,分别带有相应的背景,并将其中一个设置为INVISIBLE,另一个设置为VISIBLE。当然,这仅适用于少量的背景,例如“绿色”和“红色”,可能表示某种状态。

0
原因是通过 RemoteViews,您只能调用有限数量的方法。如果被禁止,您将收到如下消息。
汤姆

没错。你只能使用带有@RemotableViewMethod注释的方法。 - Jose_GD

0

当你运行一个2.2模拟器时,模拟器将允许此项操作,因此我猜限制在2.2中被取消了。


0

我觉得奇怪的是,这在我的Nexus One(2.2)上运行得很好,但在HTC Tattoo(1.6)上根本不行。我将尝试运行一些模拟器测试,看看是否只是HTC懒惰地实现了一些底层UI渲染代码,这已经在Tattoo上发现(布局与股票Android 1.6上的不同)。

您在哪个设备上测试这个?


我的2.1模拟器上无法运行。也许在Android 2.2中取消了这个限制?请参阅android-developers组中的此讨论:听起来这是一个众所周知的限制。 - MarkJ
现在我所做的是: views.setImageViewBitmap(R.id.background, BitmapFactory.decodeResource(context.getResources(), info.backgroundImageId) ); 这样做更加繁琐且效率较低,但它现在允许我添加可下载的主题。 - DavidG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接