Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically disable onClick handler on Android AppWidget Button

I have a Button on appwidget, that I need to 'enable'/'disable' programmatically from a Service.

First idea was to call setBoolean(R.id.buttonid, "setClickable", false) to disable it, but apparently you can't call setClickable remotely.

Another idea was was remove the text label from it with rv.setTextViewText(R.id.buttonid, "") and then remove the click handler by rv.setOnClickPendingIntent(R.id.buttonid, null). Unfortunately passing null to it causes NullPointerException in in android.app.ActivityThread.handleServiceArgs

Is there some other way to programmatically disable/enable appwidget Button? I could just call rv.setViewVisibility(R.id.buttonid, View.GONE) to hide the button completely instead of disabling it. This would however completely break whole widget layout and I would like to avoid it.

The solution I'm using now is hiding the button with setViewVisibility and showing other blank button instead to the keep appwidget layout as it was before.

like image 984
grzaks Avatar asked Apr 15 '10 17:04

grzaks


2 Answers

Basically I had the same problem, but wanted to do it entirely programmatic, so we just pass the boolean value to the setBoolean() function:

remoteViews.setBoolean(R.id.imageButton1, "setEnabled", false);

Don't forget to tell Android to update the home screen:

    RemoteViews remoteViews = new RemoteViews(context.getResources().getText(R.string.package_name).toString(), R.layout.your_layout);
    ComponentName thisWidget = new ComponentName(context, Widget.class);
    AppWidgetManager manager = AppWidgetManager.getInstance(context);
    manager.updateAppWidget(thisWidget, remoteViews);
like image 122
Henrique de Sousa Avatar answered Sep 28 '22 07:09

Henrique de Sousa


When you create your RemoteViews instance, you supply a layout. When you want to disable the button, choose a layout with android:enabled="false" on that button.

Or, you could use setOnClickPendingIntent() and supply an Intent that just will not go anywhere (e.g., a broadcast Intent for an action that nobody uses).

like image 26
CommonsWare Avatar answered Sep 28 '22 07:09

CommonsWare