Answer the question
In order to leave comments, you need to log in
How to combine widget classes?
I have several widgets of different sizes in an Android application. Accordingly, a separate class has to be allocated for each. Is it possible to somehow combine these classes into one? Maybe you can somehow move all the code to the parent class, and define only the necessary constants in the child classes?
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);
}
}
Answer the question
In order to leave comments, you need to log in
If widgets perform approximately the same role, but differ in size or style, for example, then it makes sense to create a parent abstract class with interfaces.
It is also possible, if your widgets are approximately the same, then assign the same id to their used components and move all initialization to the parent class in final void setupIU(){}. Further inherit, put the necessary contextView in each widget.
Example
public class ParentWidget extends AppWidgetProvider {
public final void setUI(){
/* инициализация одинаковых компонентов и действий для наследуемых виджетов*/
}
}
public class ChildWidget0 extends BaseWidget {
onCreate(){
super.OnCreate();
setUI();
}
public class ChildWidget1 extends BaseWidget {
onCreate(){
super.OnCreate();
setUI();
}
And what's the problem with just making descendant classes?
If necessary, add a getAction method that returns a string instead of ACTION_WIDGET_EDIT (if these events need to be separated). Likewise with markup.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question