在Android中动态更改窗口小部件中的imageview

时间:2012-02-05 05:31:45

标签: android

有人能告诉我如何动态更改图像视图中的图像。我有数据库表中的图像名称。每三秒钟后,随机图像应出现在小部件的图像视图中。

1 个答案:

答案 0 :(得分:1)

试试这个,

您需要启动一个警报,在某个特定时间后触发服务,并在那里更新您的小部件的远程视图......

将此代码放在widget类的onUpdate方法中:

AlarmManager alarm;
        final Intent intent = new Intent(context, UpdateService.class);
    final PendingIntent pending = PendingIntent.getService(context, 0,
            intent, 0);
    if (alarm == null) {
        alarm = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        long interval = 500;
        alarm.setRepeating(AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime(), interval, pending);
    }

并将此代码作为内部类放在窗口小部件类中:

    public static class UpdateService extends Service {

    BatteryInfo mBI = null;

    @Override
    public void onStart(Intent intent, int startId) {
        if (mBI == null) {
            mBI = new BatteryInfo();
            IntentFilter mIntentFilter = new IntentFilter();
            mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
            registerReceiver(mBI, mIntentFilter);
        }

        RemoteViews updateViews = buildUpdate(this);
        if (updateViews != null) {
            try {
                ComponentName thisWidget = new ComponentName(this,
                        BatteryWidget.class);
                if (thisWidget != null) {
                    AppWidgetManager manager = AppWidgetManager
                            .getInstance(this);
                    if (manager != null && updateViews != null) {
                        manager.updateAppWidget(thisWidget, updateViews);
                    }
                }

            } catch (Exception e) {
                Log.e("Widget", "Update Service Failed to Start", e);
            }
        }

        stopSelf();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            if (mBI != null)
                unregisterReceiver(mBI);
        } catch (Exception e) {
            Log.e("Widget", "Failed to unregister", e);
        }
    }

    /**
     * Build a widget update to show the current Wiktionary
     * "Word of the day." Will block until the online API returns.
     */
    public RemoteViews buildUpdate(Context context) {

        updateViews = new RemoteViews(context.getPackageName(),
                R.layout.widget1);
                updateViews.setImageViewResource(R.id.imgAnim, id);

            }
        return updateViews;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}