Tuesday, February 21, 2012

How to Disabe a button on an appwidget?


As far as I know it can not be done, since the appwiget UI manipulation is limited by the methods of the RemoteViews class.
But if you insist to do that there is a way to make it look like the button were disabled!
RemoteViews can't manipulate a buttons enabled/disabled state, but it can modify its visibility. So the trick is to have two buttons, the real one, and an other which is designed to look like the real one in disabled state, and change witch one is visible.
Lets see a simple example:
We want to have two buttons on the widget, a stop and a start button in order to stop and start some kind of functionality. Once we have started it, we can not start it agin, until we stopped it and vica versa, so we want to disable the button which can not be used right now.
The XML definition of the buttons can be like this:
<Button android:id="@+id/startbutton" android:text="Start" android:visibility="visible"></Button>
<Button android:id="@+id/startbutton_disabled" android:text="Start" android:clickable="false" 
android:textColor="#999999" android:visibility="gone"></Button>
 
<Button android:id="@+id/stopbutton" android:text="Stop"  android:visibility="gone"></Button>
<Button android:id="@+id/stopbutton_disabled" android:text="Stop" 
android:clickable="false" android:textColor="#999999" android:visibility="visible"></Button>


The code that runs when clicked on the start button will contain someting like this:
RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.widget);
remoteView.setViewVisibility(R.id.startbutton, View.GONE);
remoteView.setViewVisibility(R.id.startbutton_disabled, View.VISIBLE);
remoteView.setViewVisibility(R.id.stopbutton, View.VISIBLE);
remoteView.setViewVisibility(R.id.stopbutton_disabled, View.GONE);
AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, remoteView);


And the same for the stop button:
RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.widget);
remoteView.setViewVisibility(R.id.startbutton, View.VISIBLE);
remoteView.setViewVisibility(R.id.startbutton_disabled, View.GONE);
remoteView.setViewVisibility(R.id.stopbutton, View.GONE);
remoteView.setViewVisibility(R.id.stopbutton_disabled, View.VISIBLE);
AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, remoteView);


No comments:

Post a Comment