我正在制作桶列表应用程序,它为每个任务创建一个切换按钮,所以如果按下按钮它会从状态“false”变为“true”但是我怎么能保存它们的状态所以它们不会重新启动应用后更改? 它只适用于单个按钮,但是如何使它适用于连接到列表视图的每个切换按钮?
public class MainActivity extends AppCompatActivity {
private TaskDbHelper mHelper;
private ListView mTaskListView;
private ArrayAdapter<String> mAdapter;
SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHelper = new TaskDbHelper(this);
updateUI();
LayoutInflater myinflater = getLayoutInflater();
View myview = myinflater.inflate(R.layout.item_todo, (ViewGroup) findViewById(R.id.lld),false);
ToggleButton togglebut = (ToggleButton) myview.findViewById(R.id.toggleButton);
sp = getSharedPreferences("sp",MainActivity.MODE_PRIVATE);
if (sp.getString("sp","").equals("0")){
togglebut.setChecked(true);
} else if (sp.getString("sp","").equals("1")){
togglebut.setChecked(false);
}
if (togglebut.isChecked()){
sp.edit().putString("sp","0").apply();
} else {sp.edit().putString("sp","0").apply();
}
togglebut.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
sp = getSharedPreferences("sp",MainActivity.MODE_PRIVATE);
if (isChecked){
sp.edit().putString("sp","0").apply();
} else {
sp.edit().putString("sp","1").apply();
}
}
});
}
答案 0 :(得分:0)
您可以创建一个SharedPreference来保持按钮的状态。
这高于OnCreate:
SharedPreference sp;
这是OnCreate:
sp = getSharedPreferences("sp",Activity.MODE_PRIVATE);
String newsp = noise.getString("sp","");
int spnum;
try{
spnum = Integer.parseInt(newsp);
}catch (NumberFormatException e) {
spnum = 0;
}
sp.edit().putString("sp",Integer.toString(spnum)).apply();
ToggleButton togglebut = (ToggleButton) findViewById(R.id.togglebut);
if (sp.getString("sp","").equals("0")){
togglebut.setChecked(true);
} else if (sp.getString("sp","").equals("1")){
togglebut.setChecked(false);
}
if (togglebut.isChecked()){
sp.edit().putString("sp","0").apply();
} else {sp.edit().putString("sp","0").apply();
}
togglebut.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
sp = getSharedPreferences("sp",Activity.MODE_PRIVATE);
if (isChecked){
sp.edit().putString("sp","0").apply();
} else {
sp.edit().putString("sp","1").apply();
}
}
});