[英]Passing checkbox input from one fragment to another fragment in the same activity
我有带有复选框的片段 A 和带有 EditText 的片段 B 来编写。
当片段检查一个复选框时,我想禁用片段B的可持续下文。
Y 尝试使用共享首选项,但它不会禁用任何内容。
在片段 A 中:
CheckBox.setChecked(client.getUCheckbox);
CheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
if (b){
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPref.edit();
edit.putBoolean("CheckBox", true);
edit.apply();
}
在片段 B 中:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
realm = Realm.getDefaultInstance();
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
sharedPref.getBoolean("Checkbox",false);
}
@Override
public View onCreateView(
@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_determinaciones_parte_aguas, container, false);
ButterKnife.bind(this, root);
rellenarVista();
return root;
}
private void rellenarVista() {
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
sharedPref.getBoolean("CheckBox",false);
if (CheckBox){
disableEditText();
}
disableEditText 是一种将所有 editText 的 enable 设置为 false 的方法。
我尝试的解决方案来自这篇文章。
先感谢您。
编辑:您的disableEditText();
创建片段时,该方法仅在片段 B 的onCreateView()
中调用一次。 您应该将对片段 B 的引用传递给片段 A(或父活动)并直接在片段 A 的onCheckedChanged()
中更新复选框
您正在使用的首选项对于请求活动是私有的。
您需要将 boolean 存储在可从这两个活动访问的首选项中。 代替
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
您可以使用:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
注意:如果未选中复选框,您的onCheckedChanged()
实现不会更新标志。 这是一个修复:
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor edit = sharedPref.edit();
edit.putBoolean("CheckBox", b);
edit.apply();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.