我的小部件在尝试使用它时给了我“问题加载小部件”,我不知道为什么。
这是我的代码:
班级
public class DigitalClock extends AppWidgetProvider {
public void onUpdate(Context context,
final AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
final RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.digitalclock);
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Intent clockIntent = new Intent(context, DeskClock.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
clockIntent, 0);
views.setOnClickPendingIntent(R.id.gl, pendingIntent);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new UpdateTimeTask(context,
appWidgetManager), 1, 1000);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
private class UpdateTimeTask extends TimerTask {
RemoteViews views;
AppWidgetManager appWidgetManager;
ComponentName thisWidget;
public UpdateTimeTask(Context context, AppWidgetManager appWidgetManager) {
this.appWidgetManager = appWidgetManager;
views = new RemoteViews(context.getPackageName(), R.id.gl);
thisWidget = new ComponentName(context, DigitalClock.class);
}
@Override
public void run() {
java.util.Date noteTS = Calendar.getInstance().getTime();
String time = "kk:mm";
String date = "dd MMMMM yyyy";
views.setTextViewText(R.id.tvTime, DateFormat.format(time, noteTS));
views.setTextViewText(R.id.tvDate, DateFormat.format(date, noteTS));
appWidgetManager.updateAppWidget(thisWidget, views);
}
}
}
XML 布局
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:id="@+id/gl"
tools:ignore="UselessParent" >
<TextView
android:id="@+id/tvTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/time"
android:textColor="#cccccc"
android:textSize="80sp" />
<TextView
android:id="@+id/tvDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|bottom"
android:text="@string/date"
android:textColor="#cccccc"
android:textSize="20sp" />
</GridLayout>
</GridLayout>
显现
<receiver
android:name="com.timmo.clock.DigitalClock"
android:label="@string/app_name_dc" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="com.timmo.clock.ACTION_WIDGET_RECEIVER" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/digitalclocksettings" />
</receiver>
我是不是哪里出错了?或者计时器方法是更新我的 TextView 的错误方法吗?