Sending data from nested fragments to parent fragment

后端 未结 8 1928
情深已故
情深已故 2020-11-27 12:27

I have a Fragment FR1 that contains several Nested Fragments; FRa, FRb, FRc. These

相关标签:
8条回答
  • 2020-11-27 12:51

    Too late to ans bt i can suggest create EditText object in child fragment

    EditText tx;
    

    in Oncreateview Initialize it. then create another class for bridge like

    public class bridge{
    public static EditText text = null; 
    }
    

    Now in parent fragment get its refrence.

    EditText childedtx = bridge.text;
    

    now on click method get value

    onclick(view v){
    childedtx.getText().tostring();
    }
    

    Tested in my project and its work like charm.

    0 讨论(0)
  • 2020-11-27 12:54

    You can use share data between fragments.

    public class SharedViewModel extends ViewModel {
        private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
    
        public void select(Item item) {
            selected.setValue(item);
        }
    
        public LiveData<Item> getSelected() {
            return selected;
        }
    }
    
    
    public class MasterFragment extends Fragment {
        private SharedViewModel model;
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
            itemSelector.setOnClickListener(item -> {
                model.select(item);
            });
        }
    }
    
    public class DetailFragment extends Fragment {
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
            model.getSelected().observe(this, item -> {
               // Update the UI.
            });
        }
    }
    

    More Info ViewModel Architecture

    0 讨论(0)
提交回复
热议问题