我正在尝试在Android中实现切换小部件。但是,每当我将开关设置为“OFF”位置并关闭并重新打开我的应用程序时,它再次将自身设置为“ON”值。如何根据用户设置自己。
答案 0 :(得分:0)
我的设置屏幕,java
toggleCamera = (ToggleButton) findViewById(R.id.toggleCamera);
Boolean b = AppTypeDetails.getInstance(SettingScreen.this).getToggleStatus();
toggleCamera.setChecked(b);
toggleCamera.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (toggleCamera.isChecked()) {
AppTypeDetails.getInstance(SettingScreen.this).setToggleStatus(true);
} else {
AppTypeDetails.getInstance(SettingScreen.this).setToggleStatus(false);
}
}
});
AppTypeDetails.java
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class AppTypeDetails {
private SharedPreferences sh;
private AppTypeDetails() {
}
private AppTypeDetails(Context mContext) {
sh = PreferenceManager.getDefaultSharedPreferences(mContext);
}
private static AppTypeDetails instance = null;
public synchronized static AppTypeDetails getInstance(Context mContext) {
if (instance == null) {
instance = new AppTypeDetails(mContext);
}
return instance;
}
// get toggle Status
public boolean getToggleStatus() {
return sh.getBoolean("ToggleButton", false);
}
public void setToggleStatus(Boolean toggle) {
sh.edit().putBoolean("ToggleButton", toggle).commit();
}
public void clear() {
sh.edit().clear().commit();
}
}
这将成功运作......