Save Switch State In Android
<Switch android:gravity="center" android:id="@+id/simpleSwitch" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Sentence Notification" android:showText="true" android:textOff="No" android:textOn="Yes"/>
Java:
Button savebtn;
Switch simpleSwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); simpleSwitch = (Switch) findViewById(R.id.simpleSwitch); // initiate Switch SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyz", MODE_PRIVATE); simpleSwitch.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true)); simpleSwitch.setTextOn("On"); simpleSwitch.setTextOff("Off"); savebtn = findViewById(R.id.savebutton); savebtn.setOnClickListener(this); } @Override public void onClick(View view) { if (view.getId() ==R.id.savebutton) { if (simpleSwitch.isChecked()) { PackageManager pm = getPackageManager(); //Enable Activity pm.setComponentEnabledSetting(new ComponentName(this, com.example.bellofenglish.MainActivity.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); Toast.makeText(Setting.this,"ON",Toast.LENGTH_LONG).show(); SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit(); editor.putBoolean("NameOfThingToSave", true); editor.commit(); } else { //Disable Activity PackageManager pm = getPackageManager(); pm.setComponentEnabledSetting(new ComponentName(this, com.example.bellofenglish.MainActivity.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); Toast.makeText(Setting.this,"OFF",Toast.LENGTH_LONG).show(); SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit(); editor.putBoolean("NameOfThingToSave", false); editor.commit(); }
No comments