【问题标题】:Save Widget State保存小部件状态
【发布时间】:2010-10-27 08:48:58
【问题描述】:

文档 http://developer.android.com/guide/topics/data/data-storage.html

表明有多种方法可以保存数据,我需要在小部件中执行此操作,每次尝试保存时都会出错...

例如

      SharedPreferences settings = getSharedPreferences("NAME", 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", false);

      // Commit the edits!
      editor.commit();

错误

Description Resource    Path    Location    Type
The method getSharedPreferences(String, int) is undefined for the type AWidget

又一次尝试:

     String FILENAME = "hello_file";
     String string = "hello world!";

     FileOutputStream fos = openFileOutput("Test.txt", Context.MODE_PRIVATE);
     fos.write(string.getBytes());
     fos.close();

有错误

Description Resource    Path    Location    Type
The method openFileOutput(String, int) is undefined for the type AWidget

怎么了?我看没有提到这在小部件中不起作用,那么为什么这些示例对我不起作用?

保存这些数据的首选方法是什么?

【问题讨论】:

  • AWidget 的基本类型是什么?
  • 正如@xandy 所说,了解您所在班级的类型很重要。getSharedPreferences()Context 班级中定义。

标签: android android-widget


【解决方案1】:

所以问题是我不能在没有实质内容的情况下使用这个函数,如果我在上下文中使用上面的代码将可以正常工作。在它面前……

 SharedPreferences settings = context.getSharedPreferences("NAME", 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", false);

      // Commit the edits!
      editor.commit();

如您所见,这就是获取共享偏好所需要的一切......并且有了这个......

int[] allids = AppWidgetManager .getInstance(上下文) .getAppWidgetIds(new ComponentName(context, AwarenessWidget.class));

我可以获取我的应用的所有 ID 并调用 onupdate 并根据保存的首选项更新每个视图

如果有人需要,我可以详细说明...

让我感到困惑的是,没有人能够弄清楚那个并帮助我!现在看起来很直接!

【讨论】:

    【解决方案2】:

    我认为,如果您想保存特定小部件的状态,最好使用 View 框架中内置的保存状态机制。 SharedPreferences 对应用程序来说是全局的。因此,如果您有两个 AWidget 实例,则在运行时很难区分两者。

    相反,您可能想要覆盖:

    onRestoreInstanceState(Parcelable 状态)

    onSaveInstanceState()

    如果为您的视图启用了保存,Android 应该调用 onSaveInstanceState(),您的小部件将有机会返回一个 Parcelable,它可以稍后在 onRestoreInstanceState() 中使用它来恢复它起飞的地方。

    【讨论】:

    • 我需要做的就是将一个小部件 ID 与一个 int 相关联(它被传递到函数中)我不需要保存视图的状态...只想保存哪张图片手机重启时设置为背景
    • 我想也许我不知道你在说什么,但这是一个小部件,一个小部件没有 onSaveInstanceState
    • 这就是为什么其他人要求使用基类,因为我们无法理解这意味着什么。我假设您在 UI 模块或视图中使用小部件一词。我现在假设您的意思是应用程序小部件。如果您想要更准确的答案,请发布更多代码或提供更多上下文
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2021-06-11
    • 2020-06-08
    • 1970-01-01
    相关资源
    最近更新 更多