问题是我想在共享偏好中存储我的toogle按钮状态,这样当我返回应用程序时,我的toogle按钮将保持在之前的状态。这是某种东西你想要使用它吗。如果用户按下启用按钮意味着当他返回时它将显示该按钮将启用。到目前为止我做的是
tb_vibrate = (ToggleButton)this.findViewById(R.id.tb_vibrate);
tb_vibrate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(tb_vibrate.isChecked())
{
Toast.makeText(ProfileActivity.this, "Toggle button is on", Toast.LENGTH_LONG).show();
tb_vibrate.setChecked(true);
}
else {
Toast.makeText(ProfileActivity.this, "Toggle button is Off", Toast.LENGTH_LONG).show();
tb_vibrate.setChecked(false);
}
}
});
这是我的SharePreference类
public class NotificationManager {
private static final String PREFS_FILE_NAME = "AppNotificationManager";
private static final String VIBRATE = "vibrate";
private static final String NOTIFICATION_ALERT = "notification_alert";
private static final String NOTIFICATION_SOUND = "notification_sound";
private static final String CALL_RINGTONE = "call_ringtone";
private static final String RINGTONE_VIBRATION = "ringtone_vibrate";
public static void setVibrate(final Context ctx, final String vibrate) {
final SharedPreferences prefs = ctx.getSharedPreferences(NotificationManager.PREFS_FILE_NAME, Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString(NotificationManager.VIBRATE, vibrate);
editor.commit();
}
public static String getVibrate(final Context ctx) {
return ctx.getSharedPreferences(NotificationManager.PREFS_FILE_NAME,
Context.MODE_PRIVATE).getString(NotificationManager.VIBRATE, "");
}
}
那么如何创建我的共享偏好类来存储数据并在以后使用呢?
答案 0 :(得分:2)
您可以使用 SharedPreferences 来存储ToggleButton
的状态
SharedPreferences 类提供了一个通用框架,允许您保存和检索原始数据类型的持久键值对。您可以使用SharedPreferences保存任何原始数据:布尔值,浮点数,整数,长整数和字符串。这些数据将在用户会话中持续存在(即使您的应用程序被终止)。
示例代码
SharedPreferences sp=getSharedPreferences("Login", Context.MODE_PRIVATE);
SharedPreferences.Editor Ed=sp.edit()
tb_vibrate = (ToggleButton)this.findViewById(R.id.tb_vibrate);
tb_vibrate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(tb_vibrate.isChecked())
{
Toast.makeText(ProfileActivity.this, "Toggle button is on", Toast.LENGTH_LONG).show();
tb_vibrate.setChecked(true);
Ed.putBoolean("ISCHECKED",true);
Ed.commit();
}
else {
Toast.makeText(ProfileActivity.this, "Toggle button is Off", Toast.LENGTH_LONG).show();
tb_vibrate.setChecked(false);
Ed.putBoolean("ISCHECKED",false);
Ed.commit();
}
}
});
获取值使用以下代码
SharedPreferences preferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
boolean flag = preferences.getBoolean("ISCHECKED", false);
if(flag){
tb_vibrate.setChecked(true);
}else {
tb_vibrate.setChecked(false);
}