How to save (switch) button state in android?

后端 未结 2 661
孤街浪徒
孤街浪徒 2021-01-05 06:13

I am using SWITCH (like android toggle button ) instead of normal buttons in my andorid app. The code works fine while enabling and disabling switches. But i want to store t

相关标签:
2条回答
  • 2021-01-05 06:47

    Use shared preferences or a database to store the state of your switch. It is essential that you depend on the lifecycle methods of Activity/fragment.

    The following might help you:

    @Override
    public void onClick(View v) 
    {
        if (toggle.isChecked()) 
        {
            SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
            editor.putBoolean("NameOfThingToSave", true);
            editor.commit();
        }
        else
        {
            SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
            editor.putBoolean("NameOfThingToSave", false);
            editor.commit();
        }
    }
    

    The final nail:

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyle", MODE_PRIVATE);
        toggle.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true));
    }
    

    Edit:

    The above code is working, however I feel it is a bad practice to get the shared preference values in onCreate, its better to make a loader class which inits your app variables well beforehand in a separate thread.

    Update: Wed 24 Jul; 2019:

    Android has view model support now - this can be used to handle switch state and persist it across sessions or configuration changes.

    0 讨论(0)
  • 2021-01-05 06:55
              SharedPreferences pref = getSharedPreferences("save",MODE_PRIVATE);
                        unit.setChecked(pref.getBoolean("first", false));
    
                                if(isChecked) {
                     SharedPreferences.Editor editor = getSharedPreferences("save"MODE_PRIVATE).edit();
                                        editor.putBoolean("first", true);
                                        editor.apply();
                                        unit.setChecked(true);}
    
    else
    {
        SharedPreferences.Editor editor = getSharedPreferences("save",MODE_PRIVATE).edit();
                                    editor.putBoolean("first",false);
                                    editor.apply();
                                    kilometer.setText("Km/h");
                                    unit.setChecked(false);`enter code here`
    }
    
    0 讨论(0)
提交回复
热议问题