3 回答

TA貢獻2080條經(jīng)驗 獲得超4個贊
將更改主題的代碼放在 onCreate()/onStart()/onResume() 之外的新函數(shù)中
例子:
package ...;
import ..;
public class MainActivity(){
protected void onCreate(){
//...Your code...
}
protected void onStart(){
//...Your code, if you have onStart()...
}
protected void onResume(){
//...Your code, if you have onResume()...
}
changeTheme(int themeMode){
//Add the code as I have told below
}
}
當用戶更改單選按鈕的狀態(tài)時調(diào)用該函數(shù)。
(這很重要,因為即使您不手動更改偵聽器也是第一次調(diào)用它)。
要檢查是否是用戶更改了它,而不是 SharedPreferences 中的值,請對單選按鈕使用 onClickListener 而不是 onCheckChangedListener。這樣您就可以確定用戶更改了值而不是 SharedPreferences 中的值。在 OnClickListener 內(nèi)部,更改單選按鈕的狀態(tài),以模擬單選按鈕的工作,并進行 SharedPreferences 值更新。這只是您提到的問題的解決方法,如果您的應用經(jīng)常使用單選按鈕的狀態(tài)來執(zhí)行其他工作,請不要使用它,因為這些嵌套在自身中的偵聽器會占用大量空間和 CPU 周期。

TA貢獻1884條經(jīng)驗 獲得超4個贊
我自己找到了答案!我不知道怎么做,但我改變了這個
editor.putString("CurrentTheme","Light"); editor.apply();
對此,
editor.putBoolean("CurrentTheme",true); editor.apply();

TA貢獻1777條經(jīng)驗 獲得超3個贊
要實現(xiàn)深色/夜間主題,最好使用darktheme功能。
以下代碼是其實現(xiàn)示例:
boolean isNight = AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES
viewModel.setThemeStatus(isNight) //save the last state of theme
//to switch between light/dark
AppCompatDelegate
.setDefaultNightMode(isNight ? AppCompatDelegate.MODE_NIGHT_NO : AppCompatDelegate.MODE_NIGHT_YES)
在您的啟動器活動中:
boolean isNight = viewModel.getThemeStatus()
AppCompatDelegate.setDefaultNightMode(isNight ? AppCompatDelegate.MODE_NIGHT_NO : AppCompatDelegate.MODE_NIGHT_YES)
添加回答
舉報