【问题标题】:Save and read int - android保存并读取 int - android
【发布时间】:2012-03-06 04:20:26
【问题描述】:

我正在制作一个使用 int 设置应用程序背景的设置屏幕。它工作得很好......在当前活动中。但是一旦我离开活动,int 值就会丢失并且背景不会改变。

我想做什么:我想从我的设置活动中保存 int,然后将其导入我的其他活动并检查 int "bak" 是否等于 null、"bg"、 “bg1”或“bg2”。

我听说过 sharedPreferences,但从来没有用过。这就是为什么我打开一个新线程。

【问题讨论】:

    标签: android save int


    【解决方案1】:

    好的,添加这些全局变量

    SharedPreferences data;
    public static String filename = "whateveryou want";
    

    在 onCreate 中初始化

    data = getSharedPreferences(filename, 0);
    

    然后添加一些东西,使用它,"key" 是一个唯一的描述符,name 是你要存储的变量名

            SharedPreferences.Editor editor = data.edit();
            editor.putInt("key", name);
            editor.commit();
    

    通过这个访问它,如果不存在首选项,default 是您希望分配的变量。

    intVariable = data.getInt("key", default);
    

    编辑:

    我注意到您想使用字母,例如 bg1 等。为此,您需要使用字符串,或者使用带有 switch case 或多个 if 语句的 int。这是您可以修改的开关案例示例。只需确保将 switch case 语句放在您访问上一个代码块中的 SharedPreference 之后。

    switch (integerVariable){
        case 1: // if the intagerVariable = 1, notice the : not a ;
            // set background to BG1
        break;
        case 2: // if the intagerVariable = 2, notice the : not a ;
            // set background to BG2
        break;
    }
    

    只需根据需要添加尽可能多的 case 语句。

    【讨论】:

    • int 在导入时会被命名为“key”还是保留以前的名称? (巴克)
    • 你用你命名的任何名字导入它,它会被命名为你用于name = getString(key, default)的任何变量
    • 谢谢!它在我的代码中有效。对任何打算使用此代码的人的建议是记住 pass.edit();应替换为(在这种情况下)data.edit();或者你会想知道“通过”有什么问题。
    猜你喜欢
    • 1970-01-01
    • 2011-11-22
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多