有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在同一活动中将复选框输入从一个片段传递到另一个片段

我有带复选框的片段A和带编辑文本的片段B要写

我想在选中片段A复选框时禁用片段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

先谢谢你


共 (1) 个答案

  1. # 1 楼答案

    编辑:创建片段时,在片段B的onCreateView()中只调用一次disableEditText();方法。您应该将对片段B的引用传递给片段a(或父活动),并直接在片段a的onCheckedChanged()中更新复选框

    您使用的首选项对于请求活动是私有的

    您需要将布尔值存储在可从这两个活动访问的首选项中。而不是

    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();
    }