Search code examples
javaandroidandroid-widgetpseudocode

A widget with toggle functionality


I am trying to create a widget which has one ImageView. I want it to work like a toggle button. One a click, it should do one thing and, on another click do a different thing, and repeat.

I have stumbled a lot of tutorials on widget and many posts on stackoverflow, but no success so far. I want to do something like: On first click, start a process, change the ImageView and wait for another click to stop. I have seen a widget like this

My code so far:

private Boolean clicked = false;

...

// Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);

        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_camera);
        views.setImageViewBitmap(R.id.imageView, bitmap);

        Intent intent1 = new Intent(context, MainActivity.class);
        Intent intent2 = new Intent(context, MainActivity2.class);

        PendingIntent firstPIntent = PendingIntent.getActivity(context, 0, intent1, 0);
        PendingIntent secondPIntent = PendingIntent.getActivity(context, 0, intent2, 0);

        if(!clicked)
        {
            views.setOnClickPendingIntent(R.id.imageView, firstPIntent);
            clicked = true;
            Log.e("WIdGEt", "ONE");
        }
        else if(clicked)
        {
            views.setOnClickPendingIntent(R.id.imageView, secondPIntent);
            clicked = false;
            Log.e("WIdGEt", "TWO");
        }

Please help me with some code (or pseudocode). Thanks!


Solution

  • It just runs the firstPIntent.

    That is because clicked is always false, because clicked is (apparently) a field in your AppWidgetProvider, and an AppWidgetProvider instance only lives for one update.

    You need to adjust your logic to track your "clicked" status in a file, database, or SharedPreferences — something that will last not only after the AppWidgetProvider instance is gone, but something that will be around after your process is terminated.