片段中的SharedPreferences CheckBox

时间:2016-12-14 16:44:04

标签: android android-fragments sharedpreferences store android-sharedpreferences

嗨我明星说我是Android和语言的新手一般,我使用SharedPreferences存储不同的edittext但现在我想存储一个复选框的检查但我不知道如何存储这个值,我希望有人能帮助我。

公共类FiveFragment扩展Fragment {

EditText et133;


CheckBox ch1;


public FiveFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_five, container, false);

    SharedPreferences setting = this.getActivity().getSharedPreferences("PRESS", Context.MODE_PRIVATE);

    et133 = (EditText) view.findViewById(R.id.editText);

    ch1 = (CheckBox) view.findViewById(R.id.checkBox);

//现在????

    et133.setText(setting.getString("value133", ""));



    return view;

}

public void onStop() {
    super.onStop();
    if (et133.getText() != null) {

        SharedPreferences setting = this.getActivity().getSharedPreferences("PRESS", 0);
        SharedPreferences.Editor editor = setting.edit();
        editor.putString("value133", et133.getText().toString());

//现在???             editor.apply();

    }
}

}

2 个答案:

答案 0 :(得分:0)

您可以使用听众或使用onStop()方法执行此操作。

 ch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setting.edit().putBoolean("checkbox", isChecked).apply();
            }
        });

onStop()

 setting.edit().putBoolean("checkbox", ch1.isChecked).apply();

答案 1 :(得分:0)

在putString()之后使用editor.commit(),然后保存值