我正在尝试创建一个具有一个 ImageView 的小部件。 我希望它像切换按钮一样工作。单击一次,它应该做一件事,再单击一次,做另一件事,然后重复。
我偶然发现了很多关于 widget 的教程和 stackoverflow 上的很多帖子,但到目前为止还没有成功。我想做类似的事情:第一次单击时,启动一个进程,更改 ImageView 并等待另一次单击停止。我见过这样的小部件
到目前为止我的代码:
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");
}
请帮我一些代码(或伪代码)。谢谢!
最佳答案
It just runs the firstPIntent.
这是因为 clicked
始终为 false
,因为 clicked
(显然)是 AppWidgetProvider
中的一个字段,并且 AppWidgetProvider
实例仅存在一次更新。
您需要调整逻辑来跟踪文件、数据库或 SharedPreferences 中的“点击”状态 - 这不仅会在 AppWidgetProvider
实例结束后持续存在消失了,但是在您的进程终止后仍然存在。
关于java - 具有切换功能的小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31732064/