getDelegate() method inside a fragment?

Viewed 1293

I want to turn on the night Mode in android Fragment.

The code runs fine in the activity getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);

But we cannot use the same code inside the fragment

What is the solution of this?

Is there any alternative way of turning on the nightmode inside the fragment?

Error in the fragment

The code: ((AppCompatActivity)getActivity()).getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);

The above code refreshes the fragment and the fragment as well as the parent activity

2 Answers

((AppCompatActivity)getActivity()).getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);

You can also start this in fragment with kotlin like so:

 override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
   ....
(activity as AppCompatActivity?)!!.delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_NO
.....

}

normally you store values in shared preferences and then switch modes from an ui event

Related