简体   繁体   English

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

[英]Update the TextView of an home-screen widget on-clicking

In my app I am keeping track of a counter, which can be incremented by clicking on a widget button. 在我的应用程序中,我一直在跟踪计数器,可以通过单击小部件按钮来增加计数器。

I wanted to give the user some feedback that his clicking has added one to the counter - so i tried to add a textView above the widget button. 我想向用户提供一些反馈,表明他的点击已将其添加到计数器中-因此我尝试在小部件按钮上方添加textView。 Is there a way to update the presented number after clicking? 单击后是否可以更新显示的号码?

My code (currently shows an outdated value of the counter...): 我的代码(当前显示计数器的值已过期...):

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);
}

You need to update remoteviews contents inside WidgetBroadcastReceiver and then refresh the widget as below: 您需要更新内部remoteviews内容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);
}

Yes, there is. 就在这里。

Add and onClickStatement to your button where the user clicks (in the xml folder): 将和onClickStatement添加到用户单击的按钮(在xml文件夹中):

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

Then on your actual class, just create the following: 然后在您的实际课程中,创建以下内容:

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

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

Then, myMethod() will basically do something like: 然后,myMethod()基本上会执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM