How to Add Dark Mode in Android App (All Activity) | Android Studio Tutorial

Full Tutorial Adding Dark Mode in App (day-night style theme)

In this tutorial, we will see how to add dark mode in a new or existing app in Android Studio. very simple and easy way to implement daynight theme in all whole app. We can easily change day theme to night theme or from default mode to dark mode by using a Switch component, So let’s get started.
how to add dark mode in app android studio
In MainActivity.xml creating Switch component:
<androidx.constraintlayout.widget.ConstraintLayout 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:background=”?attr/cardbackground”
    android:orientation=”vertical”
    tools:context=”.MainActivity”> 
<androidx.cardview.widget.CardView
                android:layout_width=”match_parent”
                android:layout_height=”wrap_content”>
                <TextView
                    android:layout_width=”match_parent”
                    android:layout_height=”wrap_content”
                    android:gravity=”center”
                    android:text=”General”
                    android:textColor=”#B1B7BC”
                    android:textSize=”15dp”
                    android:textStyle=”bold” />
                <LinearLayout
                    android:layout_width=”match_parent”
                    android:layout_height=”match_parent”
                    android:layout_marginTop=”15dp”
                    android:orientation=”vertical”
                    android:padding=”10dp”>
                    <TextView
                        android:layout_width=”wrap_content”
                        android:layout_height=”wrap_content”
                        android:text=”Enable Dark Theme”
                        android:textStyle=”bold”>
                    </TextView>
                    <Switch
                        android:id=”@+id/myswitch”
                        android:layout_width=”match_parent”
                        android:layout_height=”wrap_content”
                        android:layout_marginTop=”8dp”
                        android:text=”Dark Mode” />
                   <Button
                        android:id=”@+id/neww”
                        android:layout_width=”120dp”
                        android:layout_height=”50dp”
                        android:layout_gravity=”center”
                        android:textStyle=”bold”
                        android:paddingStart=”2dp”
                        android:paddingEnd=”2dp”
                        android:text=”Next Activity”
                        android:textColor=”@color/white”
                        android:textSize=”12sp” />
                </LinearLayout>
            </androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>

Now adding function to this Switch and Saving the state(daynight theme) so that even after restarting app user will continue from where it left in MainActivity.java:

public class MainActivity extends AppCompatActivity {
public Switch myswitch;
public static SharedPref sharedPref;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        sharedPref = new SharedPref(this);
        if(sharedPref.loadNightModeState()==true) {
            setTheme(R.style.darktheme);
        }
        else setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.MainActivity);
myswitch = findViewById(R.id.myswitch);       
if (sharedPref.loadNightModeState()==true){
    myswitch.setChecked(true);
}
myswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(isChecked){
           sharedPref.setNightModeState(true);
           restartApp();
        }
        else{
          sharedPref.setNightModeState(false);
            restartApp();
        }
    }
});
//Nextactivity
        Button newactivity = findViewById(R.id.neww);
         newactivity.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
               Intent i = new Intent(getApplicationContext(),MainActivity2.class); 
              startActivity(i);  
             }
         });
Inside MainActivity declaring task for restartApp();
public void restartApp(){
        Intent i = new Intent(getApplicationContext(),MainActivity.class);
        startActivity(i);
        finish();
}
Now Creating SharedPref.java Class
public class SharedPref {
    SharedPreferences mySharedPref ;
    public SharedPref(Context context) {
        mySharedPref = context.getSharedPreferences(“filename”, Context.MODE_PRIVATE);
    }
    // this method will save the nightMode State : True or False
    public void setNightModeState(Boolean state) {
        SharedPreferences.Editor editor = mySharedPref.edit();
        editor.putBoolean(“NightMode”,state);
        editor.commit();
    }
    // this method will load the Night Mode State
    public Boolean loadNightModeState (){
        Boolean state = mySharedPref.getBoolean(“NightMode”,false);
        return  state;
    }
}
Now Open Style.xml and create a new night theme for app:
 <!– Night / dark  Mode theme. –>
    <style name=”darktheme” parent=”Theme.AppCompat.Light.DarkActionBar”>
        <!– Customize your theme here. –>
        <item name=”colorPrimary”>@color/black</item>
        <item name=”colorPrimaryDark”>#000000</item>
        <item name=”colorAccent”>@color/colorAccent</item>
        <item name=”backgroundcolor”>#1A1A1A</item>
        <item name=”cardbackground”>#292929</item>
        <item name=”textcolor”>#ffffff</item>
        <item name=”buttoncolor”>#000000</item>
    </style>
For Day theme:
<!– Base application theme. –>
    <style name=”AppTheme” parent=”Theme.AppCompat.Light.DarkActionBar”>
        <!– Customize your theme here. –>
        <item name=”colorPrimary”>@color/white</item>
        <item name=”colorPrimaryDark”>@color/colorPrimaryDark</item>
        <item name=”colorAccent”>@color/colorAccent</item>
        <item name=”backgroundcolor”>#FFFFFF</item>
        <item name=”cardbackground”>@color/gray</item>
        <item name=”textcolor”>#ffffff</item>
        <item name=”buttoncolor”>@color/brown</item>
    </style>
Now inside values create new Values Resource File named as attrs.xml:
<?xml version=”1.0″ encoding=”utf-8″?>
    <resources>
        <declare-styleable name=”ds” >
            <attr name=”backgroundcolor” format=”color” />
            <attr name=”cardbackground” format=”color” />
            <attr name=”textcolor” format=”color” />
            <attr name=”buttoncolor” format=”color” />
            <attr name=”colorPrimary” format=”color”/>
            <attr name=”colorPrimaryDark” format=”color”/>
        </declare-styleable>
</resources>
Now Creating New empty Activity name as MainActivty2. Now open MainActivity2.xml:
<androidx.appcompat.widget.LinearLayoutCompat 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:orientation=”vertical”
    android:background=”?attr/cardbackground”
    tools:context=”.MainActivity2″>
  <TextView
                            android:layout_width=”wrap_content”
                            android:layout_height=”wrap_content”
                            android:padding=”5dp”
                            android:text=”New Activity”
                            android:textAlignment=”center”
                            android:textColor=”?attr/textcolor”
                            android:textSize=”12sp”
                            android:gravity=”center_horizontal” />
</androidx.appcompat.widget.LinearLayoutCompat>
And then open MainActivity.java and calling SharedPref if Darkmode is true it will apply night theme to this activity also so let’s do this:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        sharedPref = new SharedPref(this);
        if(sharedPref.loadNightModeState()==true) {
            setTheme(R.style.darktheme);
        }
        else setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.MainActivity2);
// your codes here
}
}
NOTE: Press Alt + Enter on sharePref it will automatically import settings from MainActivity.java.
Don’t forget to add android: theme in AndroidManifest.xml:
  <activity
            android:name=”.MainActivity”
            android:theme=”@style/AppTheme” />
        <activity
            android:name=”.MainActivity2″
            android:theme=”@style/AppTheme” />
This way you can add Dark Mode into all activity of your app and save state also. So that even restarting app will show day/night theme user selected last time.
Watch video tutorial if you have any doubts

Leave a Comment