While creating an Android app, I want to create a function that allows you to set the dark mode in a dialog window created from a fragment. As a result of finding a way to set the dark mode, almost all developers use the restart activity. Is there a way to apply the dark mode immediately without restart? This is the dark mode application code in the dialog window inside the fragment I am currently using.
class MyFragment : Fragment() {
private var dialog: AlertDialg? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_my, container, false)
if (AppCompatDelegete.getDefulatNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
context!!.setTheme(R.style.DarkTheme)
} else {
context!!.setTheme(R.style.LightTheme)
}
view.darkMode.setOnClickListener {
val v = LayoutInfalter.from(context).inflate(R.layout.dialog_dark, null)
builder.setView(v)
dialog = builder.create()
dialog.show()
v.selectMode.setOnCheckedChangeListener { _, id ->
when (id) {
R.id.light -> {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
val intent = Intent(context, MainActivity::class.java)
startActivity(intent)
}
R.id.dark -> {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
val intent = Intent(context, MainActivity::class.java)
startActivity(intent)
}
}
}
}
}
}
Clicking the darkMode Button in the view that inflates fragment_my creates a v that inflates dialog_dark. Inside v, there is selectMode made of RadioGroup, and inside there are light radio button and dark radio button. When I made it as above, I confirmed that it restarts from the MainActivity when light or dark is clicked. Is it possible to immediately apply the theme change every time ligth or dark is clicked without turning off the dialog window?