Android switches Theme in three mainstream ways. The first method is to switch Theme through the built-in style, which is generally used for night mode/daytime mode switching. The second is to implement plug-in through apk, and the third is to decompress the package to the corresponding app file by downloading the zip file, and the application requires the file to be read to the memory. This article describes the first way to switch Theme from android.
First of all, create the attrs file under values, and then define some attr.
Then, define two styles in the styles file.
Then, use attrs in the layout file.
Finally, set theme in mainActivity and dynamically switch theme.
Import android. OS. bundle; import android. preference. preferenceManager; import android. annotation. suppressLint; import android. app. activity; import android. content. intent; import android. content. sharedPreferences; import android. content. sharedPreferences. editor; import android. view. view; import android. widget. button; public class MainActivity extends Activity {private Button mSwtichThemeBtn; private boolean I SNight; private SharedPreferences sp; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); sp = PreferenceManager. getdefasharsharedpreferences (this); setTheme (isNight = sp. getBoolean ("isNight", false ))? R. style. nightTheme: R. style. dayTheme); setContentView (R. layout. activity_main); mSwtichThemeBtn = (Button) this. findViewById (R. id. swtichThemeBtn); mSwtichThemeBtn. setText (isNight? "Switch daytime mode": "Switch night mode"); mSwtichThemeBtn. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {Editor edit = sp. edit (); edit. putBoolean ("isNight ",! IsNight); edit. commit (); recreateForTheme () ;}}) ;}@ SuppressLint ("NewApi") public void recreateForTheme () {if (android. OS. build. VERSION. SDK_INT> = 11) {this. recreate ();} else {this. finish (); startActivity (new Intent (MainActivity. this, MainActivity. class ));}}