2010-03-16 95 views
20

我想创建一个AppWidget,其中TextView的背景颜色随机以指定的周期性间隔更改。Android 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> 

在更新方法中,我已加载的布局

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)

回答

0

原因是,通过RemoteViews你可以调用只是有限的方法的安装。如果它被禁止,你会得到这样的消息。

Tom

+0

正是。您只能使用具有@RemotableViewMethod注释的方法 – 2013-12-12 22:08:56

1

Tomas是正确的。我的解决方案是用各自的背景制作两个视图,使一个INVISIBLE和另一个可见。当然,这只适用于少数背景,例如可能指示某种状态的“绿色”和“红色”。

0

我觉得奇怪的是,它在我的Nexus One(2.2)上效果很好,但在HTC Tattoo(1.6)上却没有。我将尝试运行一些模拟器测试,看看它不仅仅是HTC的另一种情况,它懒洋洋地实现了一些底层的UI渲染代码,我已经在Tattoo(Layouts呈现方式与Android 1.6版本不同)中找到了代码。

你在测试什么设备?

+0

不适用于我的2.1模拟器。也许限制在Android 2.2中被删除?另请参阅android- developers组上的[本讨论](http://groups.google.com/group/android-developers/browse_thread/thread/aa000a36eadafaa5/a406589560d76784#a406589560d76784):听起来像是众所周知的限制 – MarkJ 2010-09-21 09:59:19

+0

Now我做的是: views.setImageViewBitmap(R.id.background,BitmapFactory.decodeResource(context.getResources(),info.backgroundImageId)); 它更麻烦,效率更低,但现在允许我添加可下载的主题 – DavidG 2010-09-25 17:09:43

0

当你运行一个2.2模拟器时,仿真器会让它通过,所以我想这个限制从2.2开始解除。

1

从android 2.2开始,这个方法可以被调用,而不是之前。

55

试试这个可以正常工作。

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

如果我想保留drawable,该怎么办? – TheOnlyAnil 2015-08-05 19:33:43

+1

不适用于像LinearLayout这样的ViewGroups,它可以处理像TextView这样的视图 – IHeartAndroid 2015-12-26 14:45:33

+0

这个解决方案对我试过的ViewGroups起作用。 – Abdullah 2017-12-02 07:35:22

6

如果要设置文本本身的颜色,使用

remoteViews.setInt(R.id.tvAmountThisYear, "setTextColor", 
       android.graphics.Color.RED); 
2

contentView.setInt(R.id.tv_contactText, “setBackgroundColor”, 颜色。parseColor(hexColor));

+0

这对我有效.... VOILA – peter 2015-10-10 05:44:44

4

如果你有一些形状TextView的,其中的背景是在一些绘制资源定义的背景,那么你可以使用

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

在上面的代码中的语句,R.id.change是TextView的与一些背景资源,你已经在你的可绘制文件夹中定义了一些资源(my_drawable和我的drawable_new)。

<TextView 
    android:id="@+id/change" 
    android:background="@drawable/my_drawable"> 
</TextView