我的应用程序中有几个不同大小的小部件。对于每个小部件,我需要将接收器android:name设置为不同的值(否则Android只显示一个第一个小部件)。所以我需要为每个小部件创建具有相同代码的单独类。这是不安的。我怎么能避免这个?可能我可以创建一个父类并为其他小部件类继承它吗?
我的代码:
清单:
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_1x1" />
</receiver>
<receiver android:exported="false"
android:name=".WidgetHandler_4x4"
android:label="Widget 4x4" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_4x4" />
</receiver>
WidgetHandler_1x1 / WidgetHandler_4x4:
public class WidgetHandler_4x4 extends AppWidgetProvider {
public static String ACTION_WIDGET_EDIT = "ActionWidgetEdit";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
Intent editIntent = new Intent(context, this.getClass());
editIntent.setAction(ACTION_WIDGET_EDIT);
PendingIntent editPendingIntent = PendingIntent.getBroadcast(context, 0, editIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.edit_button, editPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WIDGET_EDIT)) {
Toast.makeText(context, "edit", Toast.LENGTH_SHORT).show();
}
super.onReceive(context, intent);
}
}