如何在android中保存switchcompat的状态?

时间:2017-04-21 18:48:23

标签: android switchcompat

我有这个Android应用程序,其中有使用switchcompat。我已经尝试过sharedPreferences()。我无法保存switchcompat的状态。就像当我按下并且我正在离开活动时,它会自动下降。 这是我的代码

package com.example.srushtee.dummy;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SwitchCompat;
import android.view.Menu; 
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.google.firebase.messaging.FirebaseMessaging;

public class SettingsActivity extends AppCompatActivity {

private SwitchCompat switchCompat;
private Boolean isChecked=false;
private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    switchCompat=(SwitchCompat) findViewById(R.id.switchButton);
    FirebaseMessaging.getInstance().subscribeToTopic("APP");


    switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(switchCompat.isChecked())
            {
                SharedPreferences.Editor editor=getSharedPreferences("com.example.srushtee.dummy",MODE_PRIVATE).edit();
                editor.putBoolean("True",true);
                editor.commit();

                FirebaseMessaging.getInstance().unsubscribeFromTopic("APP");



            }
            else {
                SharedPreferences.Editor editor=getSharedPreferences("com.example.srushtee.dummy",MODE_PRIVATE).edit();
                editor.putBoolean("false",false);
                editor.commit();
                FirebaseMessaging.getInstance().subscribeToTopic("APP");


            }

        }
    });

}

}

请帮忙。提前谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用开关上的setOnClickListener并保存您的状态.. sharedPreferences

 switchCompat.setOnClickListener(new View.OnClickListener() {

       @Override
       public void onClick(View arg0) {    
           SharedPreferences.Editor editor = getSharedPreferences("com.example.srushtee.dummy", MODE_PRIVATE).edit();
           editor.putBoolean("service_status", switchCompat.isChecked());
           editor.commit();
       }
   }

现在使用以下方式检索该值:在onCreate()

中调用此值
  SharedPreferences prefs = getSharedPreferences("com.example.srushtee.dummy", MODE_PRIVATE);
  boolean switchState = pref.getBoolean("service_status", false);

  if(switchState){
        //Do your work for switch is selected on
  } else {
        //Code for switch off
  }