英文:
NightMode toggle button state in Android Studio
问题
我正在使用 Android Studio 与第三方库进行工作。
GitHub 链接:https://github.com/shrikanth7698/Night-Mode-Button
夜间模式切换按钮运行良好。
我希望能在应用关闭后仍然保存其状态。
在这种情况下,toggle.setChecked(false);
不起作用,因此我们无法使用共享首选项。
我该如何实现这一目标?
英文:
I am working with a third party library in android studio.
github link: https://github.com/shrikanth7698/Night-Mode-Button
The Night mode toggle button is working fine.
I want to save its State even after the App is closed.
The toggle.setChecked(false);
is not working in this case as a result of which we cannot use shared preferences
how can I achieve it?
答案1
得分: 0
根据 Night-Mode-Button
的文档,你可以像这样使用 OnSwitchListener
来保存按钮的状态:
nightModeButton.setOnSwitchListener(new NightModeButton.OnSwitchListener() {
@Override
public void onSwitchListener(boolean isNight) {
// 将布尔值存储在 SharedPreferences 中
SharedPreferences sharedPrefs = context.getSharedPreferences(Constants.APP_NAME, MODE_PRIVATE);
sharedPrefs.edit().putBoolean("NightMode", isNight).apply();
}
});
然而,从 GitHub 页面上的问题 看来,更多人遇到了你提出的关于无法设置按钮状态的问题,而且目前似乎还没有解决方案。
因此:通过 OnSwitchListener
可以保存按钮的状态,但是目前来看,使用这个库无法设置按钮的状态。
英文:
As per the documentation of the Night-Mode-Button
, you could use the OnSwitchListener
like so to save the state of the button:
nightModeButton.setOnSwitchListener(new NightModeButton.OnSwitchListener() {
@Override
public void onSwitchListener(boolean isNight) {
// Store the boolean in SharedPreferences
SharedPreferences sharedPrefs = context.getSharedPreferences(Constants.APP_NAME, MODE_PRIVATE);
sharedPrefs.edit().putBoolean("NightMode", isNight);
});
}
However, from the issues on the GitHub page, it looks like more people are facing the issue you raised about not being able to set the button's state, and it also looks like there is no solution for it yet.
So: saving the button's state can be done through the OnSwitchListener
, but setting the button's state seems to not be possible with this library as of now.
专注分享java语言的经验与见解,让所有开发者获益!
评论