项目需求是在Widget上面有5个按钮,就是类似与电源管理的Widget那样的五个按钮, 要的效果是类似android自带的某些效果:点击某个按钮的时候其他按钮变为不可用(也就是按钮的总开关), 还有三个按钮是一组,当他们可用的时候这一组按钮中只有一个是高亮显示的,其他的都灰掉。!
先做Widget在设置按钮点击事件的时候就知道BroadcastReceiver是无法直接操作UI控件的,但是AppWidget有个RemoteViews可以去设置Widget中的控件, 于是带着这个经验,到RemoteViews类中去找setEnable(),结果发现没有! 这条路行不通,于是google了下, 发现很多人也都有这个问题! 这条路走不通,不能说功能就不做了阿!
于是我想了两个解决方案:
1:两个按钮一组(Enable和Disable的为一组), 因为RemoteViews是可以设置控件的可见程度的, 当总开关为开的时候, 显示可用的按钮,隐藏不可用的,当总开关为关的时候隐藏可用的,显示不可用的!
2:点击按钮触发的Service或者Activity里面去判断要不要处理点击事件!(点击按钮时可以把总开关的状态随着Intent传过去,也可以在Activity/Service中读取数据库)
第一种方案的实现:
<Button android:id="@+id/startbutton"
android:text="Start"
android:visibility="visible">
</Button>
<Button android:id="@+id/startbutton_disabled"
android:text="Start"
android:clickable="false"
androidandroid: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"
androidandroid:textColor="#999999"
android:visibility="visible">
</Button>
当点击startbutton的时候
RemoteViews remoteView=newRemoteView(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);
当点击stopbutton的时候
RemoteViewsremoteView=newRemoteViews(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);
其实通过一个android:clickable="false",还有button的隐藏转换造成了视觉的欺骗
第二种解决方案:
这种我只把萎代码写出来, 大家可以根据需求自行修改, 以Activity为例
Intent intent = getIntent();
if(intent.getIntExtra("btnStatus") != TURN_OFF) {
//do something
}