android - Activity 中的共享首选项 - android

标签 android save sharedpreferences state

请问如何保存状态切换按钮?我有带有加载代码的 MainActivity,它是正确的。这是在 public void onCreate 中。

SharedPreferences editor = getSharedPreferences("mymode", MODE_PRIVATE);

boolean tgpref = editor.getBoolean("tgpref", true);  //default is true

    if (tgpref == true) { //if (tgpref) may be enough, not sure
        chAppStat.setChecked(true);
    } else {
        chAppStat.setChecked(false);
    }

并且在AppInfoAdapter中保存了代码,但是在这个类中是不正确的MODE_PRIVATE。

public void onCheckedChanged( CompoundButton buttonView, boolean isChecked) {     
    if(isChecked) {
        try {
            SharedPreferences.Editor editor = getSharedPreferences(MODE_PRIVATE).edit();
            editor.putBoolean("tgpref", true); // value to store
             editor.commit();
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

如果在 MainActivity 中都是正确的,但如果在两个部分中是不正确的。请给我一些建议或示例。谢谢

最佳答案

您正在读取/保存的键值不同:

读取“tgpref

  boolean tgpref = editor.getBoolean("tgpref", true);  //default is true

并保存“thpref

SharedPreferences.Editor editor = getSharedPreferences("mymode",MODE_PRIVATE).edit();
                    editor.putBoolean("thpref", true); // value to store
                    editor.commit();

在两者中使用相同的键名“tgpref”!

更新:

现在您的 AppInfoAdapter 必须实现 OnCheckedChangeListener

public class AppInfoAdapter extends BaseAdapter implements OnCheckedChangeListener{

或将监听器设置为您的复选框:

CheckBox myCheckBox = ( CheckBox ) findViewById( R.id.repeat_checkbox );
myCheckBox .setOnCheckedChangeListener(new OnCheckedChangeListener()
{
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if ( isChecked )
        {
            //0 = MODE_PRIVATE
    SharedPreferences.Editor editor = getSharedPreferences("mymode", 0).edit();
    editor.putBoolean("tgpref", isChecked );
    editor.commit();
        }

    }
});

关于android - Activity 中的共享首选项 - android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22183088/

相关文章:

android - 如何在 Canvas 的右下角绘制小标志类型的图像?

r - 在 R 中保存并重新加载 'list' 对象

c# - 将文字添加到图像并保存

java - SharedPreferences 在检索值时返回 null

android - https ://www. googleapis.com/identitytoolkit/v3/relyingparty/sendVerificationCode 的意外响应代码 400?

android - 在 Android 应用程序中实现类似 Google map 的搜索栏

java - 无法从集合中删除整数

javascript - 保存和加载 jsPlumb 流程图,包括精确的 anchor 和连接

android - 存储位置数据的最佳方式 - Android

java - 检测到新的一天时调用方法