gpt4 book ai didi

android - 如何在android中保存switchcompat的状态?

转载 作者:行者123 更新时间:2023-11-30 00:35:08 25 4
gpt4 key购买 nike

我有这个 android 应用程序,其中使用了 switchcompat。我已经在其中尝试了 sharedPreferences() 。我无法保存 switchcompat 的状态。就像当我按下并退出 Activity 时,它会自动离开。这是我的代码

package com.example.srushtee.dummy;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SwitchCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.google.firebase.messaging.FirebaseMessaging;

public class SettingsActivity extends AppCompatActivity {

private SwitchCompat switchCompat;
private Boolean isChecked=false;
private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
switchCompat=(SwitchCompat) findViewById(R.id.switchButton);
FirebaseMessaging.getInstance().subscribeToTopic("APP");


switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(switchCompat.isChecked())
{
SharedPreferences.Editor editor=getSharedPreferences("com.example.srushtee.dummy",MODE_PRIVATE).edit();
editor.putBoolean("True",true);
editor.commit();

FirebaseMessaging.getInstance().unsubscribeFromTopic("APP");



}
else {
SharedPreferences.Editor editor=getSharedPreferences("com.example.srushtee.dummy",MODE_PRIVATE).edit();
editor.putBoolean("false",false);
editor.commit();
FirebaseMessaging.getInstance().subscribeToTopic("APP");


}

}
});

}

请帮忙。提前谢谢你

最佳答案

您可以在开关上使用 setOnClickListener 并保存您的状态..in sharedPreferences

 switchCompat.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
SharedPreferences.Editor editor = getSharedPreferences("com.example.srushtee.dummy", MODE_PRIVATE).edit();
editor.putBoolean("service_status", switchCompat.isChecked());
editor.commit();
}
}

现在使用以下方法检索值:在 onCreate()

中调用它
  SharedPreferences prefs = getSharedPreferences("com.example.srushtee.dummy", MODE_PRIVATE);
boolean switchState = pref.getBoolean("service_status", false);

if(switchState){
//Do your work for switch is selected on
} else {
//Code for switch off
}

关于android - 如何在android中保存switchcompat的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43549962/

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