Android CheckBox取消选中

时间:2019-05-17 03:15:10

标签: android android-edittext android-checkbox

我想在Android应用程序中添加保存检查。有一个CheckBox,两个EditText。 但是所有检查都无效,我的保存检查代码有问题吗?

@Override
public void onClick(View v) {
String errString = SaveCheck();
}

private String SaveCheck() {
//et_other:other transportation
//CheckCar:car
//et_mileage:mileage


CheckBox CBC = (CheckBox) findViewById(R.id.CheckCar);

if (et_other.getText() != null && !CBC.isChecked() && et_mileage.getText().toString().startsWith("0.0")) {
float temp = Float.parseFloat(et_mileage.getText().toString());
if (temp > 0.0)
    return " Fill in other transportation and the car is not checked, mileage must 0";
}

if (et_other.getText() != null && CBC.isChecked() && et_mileage.getText().toString().startsWith("0.0")) {
float temp = Float.parseFloat(et_mileage.getText().toString());
if (temp == 0.0)
    return " Fill in other transportation and check the car, mileage mustn't 0";
}
}

1 个答案:

答案 0 :(得分:0)

您可以将复选框状态保存在sharedPreference中,然后在需要的位置使用该状态,即使您终止了该应用程序并再次打开它,也可以获取上一次选中的状态。这很简单,您必须创建一个Custom首选项类并设置一些getter和setter并将其用于您的整个项目中:

您的首选项类别;-

public class AppPrefrences {

            private static SharedPreferences mPrefs;
            private static SharedPreferences.Editor mPrefsEditor;

            public static boolean isCheckBoxChecked(Context ctx) {
                mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
                return mPrefs.getBoolean("checkBoxState", true);
            }

            public static void setCheckBoxChecked(Context ctx, Boolean value) {
                mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
                mPrefsEditor = mPrefs.edit();
                mPrefsEditor.putBoolean("checkBoxState", value);
                mPrefsEditor.commit();
            }

        }

并在选中您的复选框时使用此方法,然后将状态保存在此方法中:-

AppPreference.setCheckBoxChecked(this, your checkbox state in true or false);

,当您需要该状态时,请调用此方法:-

if(isCheckBoxChecked(this)){
  // this is chaced state
}else{
  // this is not chacked state
}