How to save the state of the toogleButton on/off selection?

前端 未结 3 1830
借酒劲吻你
借酒劲吻你 2020-12-16 08:24

Hello i have implemented the application based on the toggleButton selection. but while i close that application and then reopen it, it will get in to its default selection

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 08:53

    Use SharedPreferences like erdomester suggested, but I modified little bit his code. There's some unneeded conditions.

    tg = (ToggleButton) findViewById(R.id.toggleButton1);
    
    tg.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
           SharedPreferences.Editor editor = preferences.edit();
           editor.putBoolean("tgpref", tg.isChecked()); // value to store
           editor.commit();
        }
    });
    

    And this is how to retrieve the values:

    SharedPreferences preferences = getPreferences(MODE_PRIVATE);
    boolean tgpref = preferences.getBoolean("tgpref", true);  //default is true
    
    tg.setChecked(tgpref);
    

提交回复
热议问题