gpt4 book ai didi

android - 保存开关状态android

转载 作者:行者123 更新时间:2023-11-29 19:15:20 26 4
gpt4 key购买 nike

你好,我不知道如何让我的应用程序保存开关状态
示例:
我想打开应用程序,我想在重新启动我的应用程序后关闭开关我希望我的应用程序保持关闭状态,反之亦然

public class AlgeriaNotificationsActivity extends AppCompatActivity {

public static final String PREFS_NAME = "MyPrefsFile";
private TextView switchStatus;
private Switch mySwitch;

private static final String TAG = "AlgeriaNotificationsActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_algeria_notifications);

switchStatus = (TextView) findViewById(R.id.switchStatus);
mySwitch = (Switch) findViewById(R.id.mySwitch);

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("switchkey", false);
mySwitch.setChecked(silent);

mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {

if(isChecked){
switchStatus.setText("Switch is currently ON");
}else{
switchStatus.setText("Switch is currently OFF");
}
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("switchkey", isChecked);
}
});

//check the current state before we display the screen
if(mySwitch.isChecked()){
switchStatus.setText("Switch is currently ON");
}
else {
switchStatus.setText("Switch is currently OFF");
}
}

}

最佳答案

您可以使用 SharedPreferences 同样,当开关检查事件发生时,只需将其值保存为 true,否则设置为 false。 https://developer.android.com/guide/topics/data/data-storage.html#pref

在 oncreate Activity 中检查 sharedpreference 值是否为 true 设置 switch on else set off

oncreate 检查开关值

 SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("switchkey", false);
mySwitch.setChecked(silent);

switch checkchange 中保存状态的代码

 @Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {

if(isChecked){
switchStatus.setText("Switch is currently ON");
}else{
switchStatus.setText("Switch is currently OFF");
}
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("switchkey", isChecked);
editor.commit();
}

关于android - 保存开关状态android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43725459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com