I have a widget that mostly does what I want it to (Starts an intent) but I’m wondering how I can squeeze multiple intents into one widget provider.
I have tried all the usual means of getting this done:
- Using more then one intent
- using a second widget with the same theme settings
and a few others here and there that were ultimately failures.
Generic code:
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
Intent startIntent = new Intent(context, myClass.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, startIntent, 0);
// Get the layout for the App Widget and attach an on-click listener to the button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.MyWidget);
views.setOnClickPendingIntent(R.id.startBtn, pendingIntent);
// Tell the AppWidgetManager to perform an update on the current App Widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
So I’m trying to figure out how to get more then one button on the widget. Since its set up for three and I know one of them works so I’m 1/3 the way there.
here is the XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/startBtn"
android:layout_width="150dp"
android:layout_height="75dp"
android:layout_marginBottom="5dp"
android:background="@drawable/mybg"
android:gravity="center"
android:text="First Menu Item"
/>
<TextView
android:id="@+id/startBtn2"
android:layout_width="150dp"
android:layout_height="75dp"
android:layout_marginBottom="5dp"
android:background="@drawable/mybg"
android:gravity="center"
android:text="Second menu item" />
<TextView
android:id="@+id/startBtn3"
android:layout_width="150dp"
android:layout_height="75dp"
android:layout_marginBottom="5dp"
android:background="@drawable/mybg"
android:gravity="center"
android:text="Third menu item" />
</LinearLayout>
OK, so you almost got it! The idea is to create 3 different
PendingIntentsand 3 differentIntents, and then callsetOnClickPendingIntent3 times. One for each action and button. Here is an example, assuming the three activities are myClass, myClass2, and myClass3. With the below code, each button will fire off a different intent.