我正在开发一个Android小部件。在小部件中,我有一个文本字段和两个按钮。当我按下button1时,我希望文本字段显示某个文本,如“one”,如果单击button2,文本字段将显示为“2”。
onUpdate()看起来像这样:
@Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){ super.onUpdate(context, appWidgetManager, appWidgetIds);
remoteViews = new RemoteViews(context.getPackageName(), R.layout.activity_main);
Intent intent = new Intent(context, CalculatorReceiver.class);
intent.setAction(ACTION_WIDGET_RECEIVER);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
remoteViews.setOnClickPendingIntent(R.id.one, actionPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews); }
并且onReceive()方法如下所示:
@Override public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent.getAction().equals(ACTION_WIDGET_RECEIVER)){
Toast.makeText(context, "Hi I'm 1", Toast.LENGTH_LONG).show();
}}
现在,在小部件中,我只能在按下按钮时显示Toast,但我想获取textView并更改其值。如何获取和更改textView?
答案 0 :(得分:4)
您无法从窗口小部件中获取视图的值。
您可以使用TextView
更新小部件的RemoteViews
remoteViews.setTextViewText(R.id.text_view_id, "Your text");
答案 1 :(得分:1)
请尝试在onReceive()
中添加以下行remoteViews.setTextViewText(R.id.widget_appNameView,“text view updated”);
ComponentName componentName = new ComponentName(context, WidgetProvider.class); AppWidgetManager.getInstance(context).updateAppWidget(componentName,remoteViews);