我有来自主要活动的2个广播组,我想保存他们的状态并使用数据并确定下一个活动的外观。
编辑:更新getTapCheckedOption()代码。
在mainActivity中:
@Override
protected void onCreate(Bundle savedInstanceState) {
...
SharedPreferences radioButtonPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = radioButtonPref.edit();
editor.putInt(getString(R.string.tap_checked), tapRadioGroup.getCheckedRadioButtonId());
editor.putInt(getString(R.string.time_checked), timeRadioGroup.getCheckedRadioButtonId());
editor.apply();
...}
在SecondActivity中:
@Override
protected void onCreate(Bundle savedInstanceState) {
...
SharedPreferences radioButtonPref = PreferenceManager.getDefaultSharedPreferences(this);
getTapCheckedOption(radioButtonPref);
getTimeCheckedOption(radioButtonPref);
...}
我在SecondActivity中的2个方法:
public void getTapCheckedOption(SharedPreferences sharePref) {
int checkedId = sharePref.getInt(getString(R.string.tap_checked), 0);
switch (checkedId) {
//2 buttons have always been there, if I choose one option the other will disappear.
case R.id.one_finger_radio_button:
twoFingerTap.setVisibility(View.GONE);
break;
case R.id.two_finger_radio_button:
oneFingerTap.setVisibility(View.GONE);
break;
}
}
public void getTimeCheckedOption(SharedPreferences sharePref) {
int checkedId = sharePref.getInt(getString(R.string.time_checked), 0);
switch (checkedId) {
case R.id.thirty_second_radio_button:
//countdown 30s
break;
case R.id.fifteen_second_radio_button:
//countdown 15s
break;
}
}
当我运行应用程序时,从广播组中选择选项并单击“完成”以移至SecondActivity,没有任何反应,我的2个方法中的checkedID
返回-1
。它不应该是我点击的单选按钮的ID或0
?这是正确使用SharedPreference吗?
如果我在MainActivity中默认设置一个单选按钮,例如
oneFingerButton.setChecked(true);
checkedID
始终返回该单选按钮的ID,无论选项更改如何。
答案 0 :(得分:0)
最好的方法是,使用Id
代替Intent
并使用SharedPreferences
代替Intent intent = new Intent(this,SecondActivity.class);
intent.putExtra("isOneFinger",oneFingerButton.isChecked());
intent.putExtra("isThirtySecond",thirtyButton.isChecked());
startActivity(intent);
传递数据,如
FirstActivty
boolean isOneFinger = getIntent().getBooleanExtra("isOneFinger",false);
boolean isThirtySecond = getIntent().getBooleanExtra("isThirtySecond",false);
if(isOneFinger){
// one finger pressed
}else{
// two finger pressed
}
if(isThirtySecond ){
// 30s timer
}else{
// 15s timer
}
SecondActivity
{{1}}