0
我有一個類文件,通過單擊按鈕來更改應用程序主題,並且應該在MainActivity開始保持選定主題時更改主題。使用開關保留AppTheme更改
但是,重新啓動應用程序並應用了黑暗主題後,主題重置爲默認的輕量級主題(不應該爲此),並且存在深色和淺色主題選項。
有人可能會看我的代碼或只是建議一些東西,任何幫助表示讚賞。
public class themeUtils {
private static int cTheme;
public final static int DARK = 1;
public final static int LIGHT = 0;
public static void changeToTheme(Activity activity, int theme)
{
cTheme = theme;
activity.finish();
activity.startActivity(new Intent(activity, activity.getClass()));
}
public static void onActivityCreateSetTheme(Activity activity)
{
switch (cTheme)
{
default:
case LIGHT:
activity.setTheme(R.style.AppTheme_NoActionBar);
break;
case DARK:
activity.setTheme(R.style.AppTheme_NoActionBar_Dark);
break;
}
}
}
而且MainActivity
啓動的行應該保留以前選擇的主題。
themeUtils.onActivityCreateSetTheme(this);
按鈕來設置主題
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
return builder
.setTitle("Theme")
.setNegativeButton("Dark", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
themeUtils.changeToTheme(getActivity(), themeUtils.DARK);
}
})
.setPositiveButton("Light", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
themeUtils.changeToTheme(getActivity(), themeUtils.LIGHT);
}
})
.create();
}
}
你可以在sharedPreference中存儲哪個主題處於活動狀態,並將其應用於onCreate – Berkay92
想象一下如何做到這一點,感謝您的幫助@Berkay92 –