Android implements night mode switching function, android modular framework

<?xml version="1.0" encoding="utf-8"?>

#35464e

#212a2f

#212a2f

#616161

#212a2f

@android:color/holo_blue_dark

strings.xml in values

DayNight

day mode

strings.xml in values-night

DayNight

night mode

Add click and function actions in MainActivity.java


public class MainActivity extends AppCompatActivity {

private Button mDayNightChange;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

mDayNightChange = (Button) findViewById(R.id.day_night_change);

mDayNightChange.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

int mode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;

if (mode == Configuration.UI_MODE_NIGHT_YES) {

getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);

} else if (mode == Configuration.UI_MODE_NIGHT_NO) {

getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);

}

recreate();

}

});

}

}

import android.support.v7.app.AppCompatActivity;

import android.support.v7.app.AppCompatDelegate;

You may encounter the problem of reporting red or not being able to find it, you can use the code below to replace it

import androidx.appcompat.app.AppCompatActivity;

import androidx.appcompat.app.AppCompatDelegate;

in many places

Add MyApplication.java, set the function type


import android.app.Application;

import androidx.appcompat.app.AppCompatDelegate;

public class MyApplication extends Application {

@Override

public void onCreate() {

super.onCreate();

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);

}

}

There are four types of Mode here to choose from:

MODE_NIGHT_NO: Use light theme, do not use night mode;

MODE_NIGHT_YES: use dark (dark) theme, use night mode;

MODE_NIGHT_AUTO: Automatically switch between light and dark themes according to the current time;

MODE_NIGHT_FOLLOW_SYSTEM (default option): set to follow the system, usually MODE_NIGHT_NO

end

Time really flies by in a blink of an eye. We went our separate ways and embarked on our own journeys, but even though we haven't seen each other for many years, we are still as "close" as ever because of this friendship. Don't forget the beginning of the heart. Come on, programmers, in my opinion, 35 years old and 40 years old are never a crisis, as long as you never forget why you embarked on the journey!

Finally, if you need the same information, you can **Private message me and click [ Learn ]**I am willing to share it with you!

In order to let more friends who are studying or preparing for interviews read this article, I hope you can comment, like + forward!

Thanks again to all the friends who have provided me with topics, and thank you for having you along the way!

Guess you like

Origin blog.csdn.net/m0_66264630/article/details/122945085