在appwidget android中列出

时间:2014-03-11 16:48:07

标签: android listview android-appwidget

我想在我的应用小部件中将数据显示为列表。但我是应用程序小部件的新手,所以你可以帮助我任何例子或任何参考?这是我的代码:

公共类AppWidget扩展了AppWidgetProvider {

protected static final String file_name ="user";

  @Override
  public void onUpdate(Context context, AppWidgetManager appWidgetManager,
      int[] appWidgetIds) {

    // Get all ids
    ComponentName thisWidget = new ComponentName(context,
            AppWidget.class);
    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
    for (int widgetId : allWidgetIds) {

      RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
          R.layout.widget_layout);
      //Get user name
      SharedPreferences settings = context.getSharedPreferences(file_name, 0);
      String name =  settings.getString("name", null);
      //Get data from database
      Database entry = new Database(context);
      entry.open();
      String[] myval=entry.planlist2(name);
      entry.close();

      // Set the text
      //remoteViews.setTextViewText(R.id.app_name, String.valueOf(number));
      remoteViews.setTextViewText(R.id.movie_name, Arrays.toString(myval).replaceAll("\\[|\\]", ""));

      // Register an onClickListener
      Intent intent = new Intent(context, AppWidget.class);

      intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
      intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

      PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
          0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
      remoteViews.setOnClickPendingIntent(R.id.app_name, pendingIntent);
      appWidgetManager.updateAppWidget(widgetId, remoteViews);
    }

  }

} 

现在我想将myval数据显示为列表。

1 个答案:

答案 0 :(得分:3)

你需要:

  • ListView布局

  • 中添加RemoteViews
  • 创建RemoteViewsServiceRemoteViewsFactory,基本上扮演ArrayAdapter可能在活动中的ListView中所服务的角色

    < / LI>
  • 致电setRemoteAdapter()上的RemoteViews,告知其服务可以填充ListView

the documentation涵盖了这一点,here is a sample app of mine证明了这一点。