android widget on click event

2019-01-11 17:07发布

问题:

I have created widget in android and it successfully works, but now I want to use on click event of widget so that I can open new activity from that.

Help me

回答1:

 @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                     int[] appWidgetIds) {
    for (int i = 0; i < appWidgetIds.length; i++) {
        int appWidgetId = appWidgetIds[i];

        Intent intent = new Intent(context, TaskManagerActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
        views.setOnClickPendingIntent(R.id.widget_layout, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}

In widget.xml I have root element LinearLayout with id widget_layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/widget_layout"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:paddingTop="10dip"
          android:paddingLeft="10dip"
          android:orientation="vertical">


回答2:

I used this:

// Create an Intent to launch ExampleActivity
        Intent intent = new Intent(context, Mainpage.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        remoteViews.setOnClickPendingIntent(R.id.widget, pendingIntent);


回答3:

Inside your layout, for that particular widget give

android:onClick="your method name inside your activity"

and in your activity, give:

public void methodname(View view) {
       //give your intent code here
}

Note: When you call a method like this, your method should be of public and it should have a View object as parameter.