What's the proper way to implement an Android widget with dynamically drawn content?

后端 未结 3 1198
Happy的楠姐
Happy的楠姐 2020-12-29 08:11

For my first and most awesomest Android project, I want to create a home screen widget which displays one of those Arc Clocks that all the kids are raving about these days.<

相关标签:
3条回答
  • 2020-12-29 08:36

    This works great:

    Paint p = new Paint(); 
    p.setAntiAlias(true);
    p.setStyle(Style.STROKE);
    p.setStrokeWidth(8);
    p.setColor(0xFFFF0000);
    
    Bitmap bitmap = Bitmap.createBitmap(100, 100, Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    canvas.drawArc(new RectF(10, 10, 90, 90), 0, 270, false, p);
    
    RemoteViews views = new RemoteViews(updateService.getPackageName(), R.layout.main);
    views.setImageViewBitmap(R.id.canvas, bitmap);
    
    ComponentName componentName = new ComponentName(updateService, DashboardAppWidgetProvider.class);
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(updateService);
    appWidgetManager.updateAppWidget(componentName, views);
    

    I guess the problem with your original code was just the way of drawing the arc - that's why nothing showed up.

    BTW: You can find a customizable "Arc Clock" with a very small memory footprint in the Market by searching for "arc clock"!

    0 讨论(0)
  • 2020-12-29 08:51

    To create an custom component, I would extend View or any subclass of View and override the onDraw(Canvas canvas) method to do your drawing. On the the canvas object you can call methods such as drawLine(), drawArc(), drawPicture(), drawPoints(), drawText(), drawRect(), etc.....

    Here's more details.

    Here's the api for canvas.

    I believe you can then add your custom view to a remote view for the purpose of making a widget.

    0 讨论(0)
  • 2020-12-29 08:52

    There is actually a widget called AnalogClock in the SDK that is very similar to what you are trying to do.

    It is implemented as a class that extends View and is annotated with @RemoteView. It registers receivers on Intent.ACTION_TIME_TICK and Intent.ACTION_TIME_CHANGED and draws itself by overriding the onDraw method. Check out the source. The standard AlarmClock application exposes this view as a widget that can be added to the home screen.

    I think that is a good (if not the best) way to implement what you described and obviously works well.

    0 讨论(0)
提交回复
热议问题