当前位置:  开发笔记 > Android > 正文

Android Widget更改背景颜色

如何解决《AndroidWidget更改背景颜色》经验,为你挑选了1个好方法。

我一直在寻找如何使小部件的背景更改颜色的方法,我试图在活动中放置一个适合该图标的图标并对其进行更改,但这种方法不起作用。我尝试创建一个可以更改它的服务,但是那似乎太过残酷了,对我不起作用。有人说将其更改为可绘制对象。

这是我的代码,主要活动

public class MainActivity extends AppWidgetProvider {
private static int layoutId;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    super.onUpdate(context, appWidgetManager, appWidgetIds);
    RemoteViews updateViews;
    for (int i = 0; i < appWidgetIds.length; i++) {
        int appWidgetId = appWidgetIds[i];

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main);
        layoutId = R.layout.activity_main;

        Random rnd = new Random();
        int bgcolor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
        //updating current widget
        views.setInt(layoutId, "setBackgroundResource", R.color.colorPrimaryDark);

        updateViews = new RemoteViews(context.getPackageName(),layoutId);

        AppWidgetManager.getInstance(context).updateAppWidget(
                new ComponentName(context, MainActivity.class), updateViews);

        }
    }
}

activity_main.xml

    


   


Android清单

 


    

        
            
                
            
            
        


    

颜色资源


    #3F51B5
    #303F9F
    #FF4081
    #FFFFFF

Widget.xml

    


我实际上需要它来更改随机颜色,但它甚至不会更改一种颜色。我如何改变它?



1> StephanM..:

在定义主窗口小部件布局的布局中,我必须添加以下内容:android:id =“ @ + id / LineaRLayout1”

然后在AppWidgetProvider中,onUpdate最终看起来像这样,我在这里真正展示的是如何更改颜色

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    final int N = appWidgetIds.length;

    Log.d(LOG_TAG, "Updating Example Widgets.");

    // Perform this loop procedure for each App Widget that belongs to this
    // provider
    for (int i = 0; i < N; i++) {
        int appWidgetId = appWidgetIds[i];

        // Create an Intent to launch ExampleActivity
        Intent intent = new Intent(context, WidgetActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        // Get the layout for the App Widget and attach an on-click listener
        // to the button
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main);

        //try change color here with no luck, I tried activity_main,background, widget1

        views.setInt(R.id.LineaRLayout1, "setBackgroundColor", Color.GREEN);
        views.setOnClickPendingIntent(R.id.button, pendingIntent);
        // Tell the AppWidgetManager to perform an update on the current app
        // widget
        appWidgetManager.updateAppWidget(appWidgetId, views);

推荐阅读
刘美娥94662
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有