android widget on click event

前端 未结 3 1506
不思量自难忘°
不思量自难忘° 2020-12-03 10:03

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

相关标签:
3条回答
  • 2020-12-03 10:35
     @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">
    
    0 讨论(0)
  • 2020-12-03 10:57

    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.

    0 讨论(0)
  • 2020-12-03 10:59

    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);
    
    0 讨论(0)
提交回复
热议问题