【发布时间】:2020-04-04 02:35:12
【问题描述】:
我使用切换按钮选择主题。我的目标是在首次打开应用程序时选择 theme_light 切换按钮。我使用 SharedPreferencs 保持主题状态,因为我在应用程序中使用了 recreate () 函数。 这是我的代码;
<com.google.android.material.button.MaterialButtonToggleGroup
android:id="@+id/theme_toggle_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
app:selectionRequired="true"
app:singleSelection="true"
app:checkedButton="@+id/theme_light">
<com.google.android.material.button.MaterialButton
android:id="@+id/theme_light"
style="?attr/materialButtonOutlinedStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="8dp"
android:paddingEnd="12dp"
android:minWidth="0dp"
android:text="@string/light_theme"
app:icon="@drawable/ic_brightness_7_black_24dp"
app:iconPadding="4dp"
android:onClick="theme__light"
android:textColor="?attr/buttoncolor"/>
<com.google.android.material.button.MaterialButton
android:id="@+id/theme_dark"
style="?attr/materialButtonOutlinedStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="8dp"
android:paddingEnd="12dp"
android:minWidth="0dp"
android:text="@string/dark_theme"
app:icon="@drawable/ic_brightness_4_black_24dp"
app:iconPadding="4dp"
android:onClick="theme__dark"
android:textColor="?attr/buttoncolor"/>
</com.google.android.material.button.MaterialButtonToggleGroup>
对于MainActivity;以下是在onCreate函数中。
sharedPreferences=this.getPreferences(Context.MODE_PRIVATE);
checked=sharedPreferences.getInt("cek",0);
if (checked==1){
AppCompatDelegate.setDefaultNightMode(darktheme);
materialButtonToggleGroup.addOnButtonCheckedListener((group, checkedId, isChecked) -> {
group.check(R.id.theme_dark);
});
}
else {
AppCompatDelegate.setDefaultNightMode(defaultheme);
materialButtonToggleGroup.addOnButtonCheckedListener((group, checkedId, isChecked) -> {
group.check(R.id.theme_light);
});
}
public void theme__dark(View view) {
AppCompatDelegate.setDefaultNightMode(darktheme);
checked=1;
SharedCheckTheme();
}
public void theme__light(View view) {
AppCompatDelegate.setDefaultNightMode(defaultheme);
checked=2;
SharedCheckTheme();
}
public void SharedCheckTheme(){
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("cek",checked);
editor.apply();
recreate();
}
【问题讨论】:
标签: java android material-design android-togglebutton