Created
August 4, 2024 21:01
-
-
Save klebercode/7cad44e8d729c51d933b5f81b35a20a5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.nightmodebutton | |
import android.os.Bundle | |
import android.widget.CompoundButton | |
import androidx.appcompat.app.AppCompatActivity | |
import androidx.appcompat.app.AppCompatDelegate | |
import com.google.android.material.switchmaterial.SwitchMaterial | |
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
// initialize variable | |
val switchBtn: SwitchMaterial = findViewById(R.id.switchBtn) | |
supportActionBar?.title = "LIGHT-NIGHT MODE SWITCH" | |
// switch theme mode per user wishes | |
// setting onCheckedListener on switch | |
switchBtn.setOnCheckedChangeListener { buttonView, isChecked -> | |
// checking if the switch is turned on | |
if (isChecked) { | |
// setting theme to night mode | |
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) | |
buttonView.text = "Night Mode" | |
} else { | |
// setting theme to light theme | |
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) | |
buttonView.text = "Light Mode" | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment