How to create a widget from an activity?

1

I already have the widget, add it in the manifest, the interface and the functionality of it

What I want is that through a button in an activty, the widget is put, this so that the user can put and / or remove the widget from an activity

Can this be done ???

Thanks

    
asked by Desan 06.04.2018 в 00:39
source

1 answer

0

You need to extend the AppWidgetProvider class in your application. See a tutorial here and be sure to follow the design guidelines .

** A small example:

The widget has an image and when the image is touched, the application should start. Looking for a fragment.

public class MyWidget extends AppWidgetProvider
{
    //Crear una intención para iniciar la actividad
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds)
    {
    super.onUpdate(context, appWidgetManager, appWidgetIds);

    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.home_widget);
    //Cuando hacemos clic en el widget, queremos abrir nuestra actividad principal.
    Intent launchActivity = new Intent(context, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, launchActivity, 0);
    remoteViews.setOnClickPendingIntent(R.id.widget, pendingIntent);;

    ComponentName thisWidget = new ComponentName(context, MyWidget.class);
    AppWidgetManager manager = AppWidgetManager.getInstance(context);
    manager.updateAppWidget(thisWidget, remoteViews);
    }
}

Widget design:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/widgetLauncher"
        android:layout_width="258dp"
        android:layout_height="54dp"
        android:layout_centerInParent="true"
        android:src="@drawable/wgt_logo" >
    </ImageView>

</RelativeLayout>
  

Here is a link of interest.

    
answered by 07.04.2018 в 17:57