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

前端 未结 3 1829
借酒劲吻你
借酒劲吻你 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:39

    The best way, you can set tgbutton same

    screen main

    Intent intent = new Intent(this, Something.class);
    intent.putExtra(BOOLEAN_VALUE, Boolean.valueOf((tvConfigBoolean.getText().toString())));
                startActivity(intent);
    

    screen something

    Bundle bundle = getIntent().getExtras();
    tbtConfigBoolean.setChecked((bundle
                        .getBoolean(MainActivity.BOOLEAN_VALUE)));
    

    and save state

    editor.putBoolean("BooleanKey", tbtConfigBoolean.isChecked());
            editor.commit();
    

    good luck

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-16 09:01

    Use SharedPreferences.

    tg = (ToggleButton) findViewById(R.id.toggleButton1);
    
    tg.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
    
        if((tg.isChecked()))
            {
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putBoolean("tgpref", true); // value to store
                    editor.commit();
            }
            else
            {
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putBoolean("tgpref", false); // 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
    if (tgpref = true) //if (tgpref) may be enough, not sure
    {
      tg.setChecked(true);
    }
    else
    {
      tg.setChecked(false);
    }
    

    I did not verify this code, but look at some examples on the net, it is easy!

    0 讨论(0)
提交回复
热议问题