Send data from activity to fragment in Android

前端 未结 20 3095
悲哀的现实
悲哀的现实 2020-11-21 05:13

I have two classes. First is activity, second is a fragment where I have some EditText. In activity I have a subclass with async-task and in method doInBa

20条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 05:14

    This answer may be too late. but it will be useful for future readers.

    I have some criteria. I have coded for pick the file from intent. and selected file to be passed to particular fragment for further process. i have many fragments having the functionality of File picking. at the time , every time checking the condition and get the fragment and pass the value is quite disgusting. so , i have decided to pass the value using interface.

    Step 1: Create the interface on Main Activity.

       public interface SelectedBundle {
        void onBundleSelect(Bundle bundle);
       }
    

    Step 2: Create the SelectedBundle reference on the Same Activity

       SelectedBundle selectedBundle;
    

    Step 3: create the Method in the Same Activity

       public void setOnBundleSelected(SelectedBundle selectedBundle) {
           this.selectedBundle = selectedBundle;
       }
    

    Step 4: Need to initialise the SelectedBundle reference which are all fragment need filepicker functionality.You place this code on your fragment onCreateView(..) method

        ((MainActivity)getActivity()).setOnBundleSelected(new MainActivity.SelectedBundle() {
              @Override
             public void onBundleSelect(Bundle bundle) {
                updateList(bundle);
            }
         });
    

    Step 5: My case, i need to pass the image Uri from HomeActivity to fragment. So, i used this functionality on onActivityResult method.

    onActivityResult from the MainActivity, pass the values to the fragments using interface.

    Note: Your case may be different. you can call it from any where from your HomeActivity.

     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent  data) {
           selectedBundle.onBundleSelect(bundle);
      }
    

    Thats all. Implement every fragment you needed on the FragmentClass. You are great. you have done. WOW...

提交回复
热议问题