如果用户创建了多个小部件,则在单击时更新小部件

时间:2015-08-07 00:20:43

标签: android android-widget

我的应用是Android小部件。它在主屏幕上添加了一个按钮;如果用户点击此Button,它将打开一个窗口。此窗口正在等待用户输入。它必须写一个值,这个值将改变Button中的文本。

问题是如果用户创建了许多小部件并点击任何小部件中的Button并写入一个值,则该值将仅在最后创建的小部件上设置。

如何在其小部件上制作Button更改文字?

这是我的代码

public class Widget_note extends AppWidgetProvider {

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
    }
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        the_context =  context ;
        the_appWidgetManager = appWidgetManager ;
        the_appWidgetIds = appWidgetIds ;

        Intent open_activity087 = new Intent();
        open_activity087.setClassName("syr.hamza.app.mynotes_v2", "syr.hamza.app.mynotes_v2.SetWidgetValue");
        open_activity087.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(open_activity087); 
        /*this will be open activity Immediately after creating widget to enter a value 
        * and will calling a set_value_in_widget() Function (at Below) with the value 
        * and this don't have any problem*/

        Intent intent2 = new Intent(context, EditWidgetValue.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent2, 0);
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        views.setOnClickPendingIntent(R.id.widget_button, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetIds,views);
        /* this will be open activity if clicked on the button and get the value from user
        * and calling set_value_in_widget() Function
        * here is a problem */
    }

    public static Context the_context ;
    public static AppWidgetManager the_appWidgetManager ;
    public static int[] the_appWidgetIds ;

    public static void set_value_in_widget(String value) {

        RemoteViews views2 = new RemoteViews(the_context.getPackageName(), R.layout.widget_layout);
        views2.setTextViewText( R.id.widget_button , value ) ;
        the_appWidgetManager.updateAppWidget(the_appWidgetIds, views2   );   
    }
}

1 个答案:

答案 0 :(得分:0)

将窗口小部件实例创建后的所有ID保存到SharedPreferences中,并在OnUpdate上从首选项中读取它,然后使用the_appWidgetIds。此外,您还需要将它们从onDelete的首选项中删除。