Android Studio - How can I let Switch be checked after restarting the app

折月煮酒 提交于 2019-12-11 16:50:26

问题


I only have a switch toggle on my fragment. What is the app doing now: The user opens the app and selects "Laptop" over the navigation drawer and then he sees a switch (it is a "slider" which you can move to on or off...hope you understand what I mean). The user sets switch to ON then closes the app and reopens it and the switch is off...but it shouldn't be off...it should be on, like the user sets it How can I do that? The switch should save its state, how the user selects it Do I need mysql or something?

I hope you understand what I mean

Thanks


回答1:


you should use SharedPreferences like so:

 public static final String SWITCH_PREFS = "Switcher";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

        Switch switcher = (Switch)findViewById(R.id.yourSwitchId);
        switcher.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(yourContext).edit();
                editor.putBoolean(SWITCH_PREFS,isChecked);
                editor.commit();
            }
        });
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(yourContext);
        if(prefs.contains(SWITCH_PREFS) && switcher != null)
        {
            switcher.setChecked(prefs.getBoolean(SWITCH_PREFS,false));
        }

    }

Didn't try this code, but hope this works.



来源:https://stackoverflow.com/questions/24888575/android-studio-how-can-i-let-switch-be-checked-after-restarting-the-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!