【发布时间】:2018-09-24 19:08:40
【问题描述】:
我实现了两个开关,一次只能有一个为真,现在我正在尝试保存开关的状态。我查看了与我类似的其他 StackOverflow 问题,但有些问题不起作用。这是我的代码:
public class StartingActivity extends AppCompatActivity
{
private Switch hourly, salary;
private Boolean hrlySwitch, slrySwitch;
private Double hrly, slry, tax;
private SharedPreferences pref;
private static String TAG = "tag";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting);
pref = getApplicationContext().getSharedPreferences("switchInfo", MODE_PRIVATE);
hourly = (Switch)findViewById(R.id.hourly);
salary = (Switch)findViewById(R.id.salary);
//get Bool SharedPreference
hourly.setChecked(pref.getBoolean("hrlyBool", false));
salary.setChecked(pref.getBoolean("slryBool", true));
//switching
salary.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (salary.isChecked())
{
hourly.setChecked(false);
slrySwitch = true;
hrlySwitch = false;
}
else
{
hourly.setChecked(true);
slrySwitch = false;
hrlySwitch = true;
}
}
});
hourly.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (hourly.isChecked())
{
salary.setChecked(false);
slrySwitch = false;
hrlySwitch = true;
}
else
{
salary.setChecked(true);
slrySwitch = true;
hrlySwitch = false;
}
}
});
Log.d(TAG,"before switch rule");
//put switch rule
SharedPreferences.Editor editor = pref.edit();
Log.d(TAG,"pref.edit()");
editor.putBoolean("hrlyBool",hrlySwitch);
Log.d(TAG,"putBool hourly");
editor.putBoolean("slryBool", slrySwitch);
Log.d(TAG,"putBool salary");
editor.commit();
Log.d(TAG,"after switch rule");
}
}
我包含了日志语句来跟踪我的应用程序崩溃的位置,执行的最后一行代码是“pref.edit()”日志语句。但我不确定为什么我的 putBoolean 会导致问题。
【问题讨论】:
标签: android sharedpreferences uiswitch