我的应用程序中几乎没有大小不同的小部件。对于每个小部件,我需要将接收器 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);
}
}