Hello friend today we will learn about How to save state of Switch in android.Today we use switch in many ways in our app like to change dark mode or theme.
activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Switch"
android:textColor="@color/purple_500"
android:textSize="20sp"
android:textStyle="bold" />
<androidx.appcompat.widget.SwitchCompat
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="197dp" />
</LinearLayout>
MainActivity
package com.example.darkmode;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
public class MainActivity extends AppCompatActivity {
SwitchCompat switchCompat;
Button btn;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=findViewById(R.id.secondActivity);
switchCompat=findViewById(R.id.switch1);
SharedPreferences sharedPreferences = getSharedPreferences("share", MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
switchCompat.setChecked(sharedPreferences.getBoolean("isOpen", true));
switchCompat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (switchCompat.isChecked()) {
editor.putBoolean("isOpen", true);
editor.apply();
switchCompat.setChecked(true);
Toast.makeText(SecondActivity.this, "Switch Open ...", Toast.LENGTH_SHORT).show();
} else {
editor.putBoolean("isOpen", false);
editor.apply();
switchCompat.setChecked(false);
Toast.makeText(SecondActivity.this, "Switch Close ...", Toast.LENGTH_SHORT).show();
}
}
});
}
}
0 Comments
Please do not enter any spam link in the comment box
Emoji