要实现Android Studio的主题切换,可以按照以下步骤进行操作:
settings.gradle文件,并添加以下代码:if (JavaVersion.current().isJava8Compatible()) {
extra["android.useAndroidX"] = "true"
extra["android.enableJetifier"] = "true"
}
build.gradle文件中添加以下代码:dependencies {
implementation 'androidx.appcompat:appcompat:1.3.0'
}
styles.xml文件中添加两个主题样式,例如:
AndroidManifest.xml文件中设置默认的主题,例如:
...
public void switchTheme() {
int currentTheme = R.style.AppTheme_Light;
int newTheme = R.style.AppTheme_Dark;
if (getApplicationContext().getThemeResId() == currentTheme) {
newTheme = currentTheme;
currentTheme = R.style.AppTheme_Light;
}
getApplicationContext().setTheme(newTheme);
recreate();
}
在以上代码中,switchTheme()方法用于切换主题。首先,获取当前的主题样式资源ID,然后根据当前主题选择要切换的新主题样式资源ID。最后,通过setTheme()方法设置新的主题样式,并调用recreate()方法重新创建Activity以应用新的主题。
注意:需要在Activity的onCreate()方法之前调用setTheme()方法才能正确切换主题。