【发布时间】:2020-07-03 20:27:37
【问题描述】:
我有带有复选框的片段 A 和带有 EditText 的片段 B 要写入。
当 Fragment A 复选框被选中时,我想禁用 Fragment B 的 Edittext。
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 的方法。
我尝试的解决方案来自这篇文章。
Passing Checkbox input from one fragment to another
提前谢谢你。
【问题讨论】:
-
您可以使用共享 ViewModel 限定 Activity 的生命周期,在 Fragment 之间共享数据。请参阅文档developer.android.com/topic/libraries/architecture/…。
标签: java android android-fragments