'How to open a specific Fragment when clicking on a home screen widget

How to open a specific Fragment when clicking on a home screen widget, I can already open an Activity but I have no idea about how to open a fragment from a widget this is my widget class

public class MyWidget extends AppWidgetProvider {
ComponentName watchWidget;
RemoteViews remoteViews;
private static final String SYNC_CLICKED = "automaticWidgetSyncButtonClick";

void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                     int appWidgetId) {



    remoteViews = new RemoteViews(context.getPackageName(), R.layout.My_widgets);
    watchWidget = new ComponentName(context, MyWidget.class);
    remoteViews.setTextViewText(R.id.appwidget_text,"Widget Example");
    // start Activity from the widget

    Intent configIntent = new Intent(context, MainActivity.class);
    PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);
    remoteViews.setOnClickPendingIntent(R.id.widget_container, configPendingIntent);
    appWidgetManager.updateAppWidget(watchWidget, remoteViews);
}

So any idea?



Solution 1:[1]

For the Navigation component use deep links

Manifest: Add this line to your activity section in the android manifest

<activity>
    <nav-graph android:value="@navigation/main_nav_graph" />
</activity>

Navigation graph:

<fragment
...>
 <deepLink
            android:id="@+id/deepLink"
            app:uri="myapp://example.com/text" />
</fragment>

ExWidget.kt: Declare your pending intent in your widget file.

val pendingIntent = NavDeepLinkBuilder(context)
                .setGraph(R.navigation.main_nav_graph)
                .setDestination(R.id.your_fragment)
                .setArguments(
                    YourFragmentArgs.Builder(arguments
                    ).build().toBundle())
                .createPendingIntent()

and assign this pendingIntent in the setOnClickPendingIntent method,

val views = RemoteViews(context.packageName, R.layout.example_widget)   
views.setOnClickPendingIntent(R.id.example_widget_button, pendingIntent)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kaushal Vasava