gpt4 book ai didi

android - 如何将单选按钮状态保存到保存/共享首选项?

转载 作者:搜寻专家 更新时间:2023-11-01 08:37:29 24 4
gpt4 key购买 nike

我可以在已保存的首选项中保存字符串,但无法保存单选按钮。

public class PersonalDetailsf extends Activity {

private SharedPreferences sharedPreferences;

private RadioGroup radioGroup;
private RadioButton radioSexButton;
private RadioButton rdoMale;

这是我的创建:

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

String strAge = Integer.toString(age);
String strHeight = Integer.toString(height);
String strWeight = Integer.toString(weight);

name = loadSavedPreference("name");
strAge = loadSavedPreference("strAge");
strHeight = loadSavedPreference("strHeight");
strWeight = loadSavedPreference("strWeight");

etName.setText(name);
etAge.setText(strAge);
etHeight.setText(strHeight);
etWeight.setText(strWeight);

这是在按钮后面的 onCLick 中,我在其中使用单选按钮并保存字符串:

            Name = etName.getText().toString();
age = (int) Double.parseDouble(etAge.getText().toString());
height = (int) Double.parseDouble(etHeight.getText().toString());
weight = (int) Double.parseDouble(etWeight.getText().toString());


int selectedId = radioGroup.getCheckedRadioButtonId();

radioSexButton = (RadioButton) findViewById(selectedId);
rdoMale = (RadioButton) findViewById(R.id.rdoMale);

if(rdoMale.isChecked())
{
BMR = 10 * weight + 6.25 * height - 5 * age + 5;

}
else
{
BMR = 10 * weight + 6.25 * height - 5 * age -161;

}


//Save Preferences
String strAge = Integer.toString(age);
String strHeight = Integer.toString(height);
String strWeight = Integer.toString(weight);

name = etName.getText().toString();
savePreference("name",name);

strAge = etAge.getText().toString();
savePreference("strAge",strAge);

strHeight = etHeight.getText().toString();
savePreference("strHeight",strHeight);

strWeight = etWeight.getText().toString();
savePreference("strWeight",strWeight);

最佳答案

同时创建保存和加载方法:

保存方式

public void saveRadioButtons(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("Gender", radioSexButton.isChecked());
editor.putBoolean("Male", rdoMale.isChecked());
editor.apply();
}

加载方式

public void loadRadioButtons(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
radioSexButton.setChecked(sharedPreferences.getBoolean("Gender", false));
rdoMale.setChecked(sharedPreferences.getBoolean("Male", false));
}

所以要保存您的按钮状态,只需调用saveRadioButtons()

并且要加载您的按钮状态,只需在您的代码中的某处调用loadRadioButtons(),例如您的onCreate()

希望对你有帮助

关于android - 如何将单选按钮状态保存到保存/共享首选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35601149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com