Android studio, widget button image change

+1 Faried Ahmed · March 5, 2015
Hi Peeps

I'm struggling with a "widget image issue". I created a torch widget, the default image is torch_off. When I click on the widget (switching torch on) I would like the widget to show the torch_on image,. Then when I click the widget again,  (torch off )the widget should go back to the torch_off image. I'm using Android studio. Can this be done within and XML file or should it be done within an activity. I have no clue as to which one would be best or even where to start. 

Post a Reply

Replies

Oldest  Newest  Rating
0 Faried Ahmed · March 6, 2015
Ok I got it to work

In My Widget Receiver

public class FlashlightWidgetReceiver extends BroadcastReceiver {
    private static boolean isLightOn = false;
    private static Camera camera;


    @Override
    public void onReceive(Context context, Intent intent) {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
        if(isLightOn) {
            views.setImageViewResource(R.id.mainbtn, R.drawable.ic_torch_off);


        } else {

            views.setImageViewResource(R.id.mainbtn, R.drawable.ic_torch_on);

        }

        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        appWidgetManager.updateAppWidget(new ComponentName(context, Widget.class),
                views);

        if (isLightOn) {
            if (camera != null) {
                camera.stopPreview();
                camera.release();
                camera = null;
                isLightOn = false;

            }

        } else {
            // Open the default i.e. the first rear facing camera.
            camera = Camera.open();

            if(camera == null) {


            } else {
                // Set the torch flash mode
                Camera.Parameters param = camera.getParameters();
                param.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                try {
                    camera.setParameters(param);
                    camera.startPreview();
                    isLightOn = true;


                } catch (Exception e) {


                    return;
                }
            }
        }
    }
}


aaaaaaaand :)

This is my layout 

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"

    android:padding="@dimen/widget_margin"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:id="@+id/mainbtn"
    android:src="@drawable/ic_torch_off">

</ImageView>
  • 1

Java / Android Development

106,993 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator