单击更新主屏幕小部件的TextView

时间:2017-10-08 11:29:28

标签: android onclick textview android-widget

在我的应用程序中,我正在跟踪一个计数器,可以通过单击一个小部件按钮来增加计数器。

我想给用户一些反馈,他的点击已经向计数器添加了一个 - 所以我试图在widget按钮上方添加一个textView。有没有办法在点击后更新显示的数字?

我的代码(目前显示计数器的过时值...):

for (int appWidgetId : appWidgetIds) {

    Intent incCounter = new Intent(context, WidgetBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, incCounter, 0); //braodcasting to a counter changing module

    RemoteViews ButtonCounterView = new RemoteViews(context.getPackageName(), R.layout.home_screen_widget);
    ButtonCounterView.setOnClickPendingIntent(R.id.widgetCounterButton, pendingIntent);

    String updatedCounter = String.valueOf(countersMap.getInt(todaysDate.getDate(), 0));
    ButtonCounterView.setTextViewText(R.id.widgetCounter, updatedCounter);

    appWidgetManager.updateAppWidget(appWidgetId, ButtonCounterView);
}

2 个答案:

答案 0 :(得分:0)

您需要更新WidgetBroadcastReceiver内的远程视图内容,然后按如下方式刷新小部件:

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());
ComponentName thisWidget = new ComponentName(getApplication(), YourWidget.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds) {
  appWidgetManager.updateAppWidget(widgetId, remoteViews);
}

答案 1 :(得分:-1)

是的,有。

将onClickStatement添加到用户点击的按钮(在xml文件夹中):

<Button android:id="@+id/mybutton"
    android:text="Click me!"
    android:onClick="myMethod" />

然后在您的实际课程中,只需创建以下内容:

Button btn = (Button) findViewById(R.id.mybutton);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        myMethod();
    }
});

然后,myMethod()基本上会做类似的事情:

textView.setText("Enter text that says user has added one to the counter")