Send data from activity to fragment in Android

前端 未结 20 2752
悲哀的现实
悲哀的现实 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:24

    Sometimes you can receive Intent in your activity and you need to pass the info to your working fragment.
    Given answers are OK if you need to start the fragment but if it's still working, setArguments() is not very useful.
    Another problem occurs if the passed information will cause to interact with your UI. In that case you cannot call something like myfragment.passData() because android will quickly tells that only the thread which created the view can interact with.

    So my proposal is to use a receiver. That way, you can send data from anywhere, including the activity, but the job will be done within the fragment's context.

    In you fragment's onCreate():

    protected DataReceiver dataReceiver;
    public static final String REC_DATA = "REC_DATA";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    
    
        data Receiver = new DataReceiver();
        intentFilter = new IntentFilter(REC_DATA);
    
        getActivity().registerReceiver(dataReceiver, intentFilter);
    }
    
    private class DataReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
            int data= intent.getIntExtra("data", -1);
    
            // Do anything including interact with your UI
        }
    }
    

    In you activity:

    // somewhere
    Intent retIntent = new Intent(RE_DATA);
    retIntent.putExtra("data", myData);
    sendBroadcast(retIntent);
    
    0 讨论(0)
  • 2020-11-21 05:27

    Also You can access activity data from fragment:

    Activity:

    public class MyActivity extends Activity {
    
        private String myString = "hello";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_my);
            ...
        }
    
        public String getMyData() {
            return myString;
        }
    }
    

    Fragment:

    public class MyFragment extends Fragment {
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
            MyActivity activity = (MyActivity) getActivity();
            String myDataFromActivity = activity.getMyData();
            return view;
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:32

    Basic Idea of using Fragments (F) is to create reusable self sustaining UI components in android applications. These Fragments are contained in activities and there are common(best) way of creating communication path ways from A -> F and F-A, It is a must to Communicate between F-F through a Activity because then only the Fragments become decoupled and self sustaining.

    So passing data from A -> F is going to be the same as explained by ρяσѕρєя K. In addition to that answer, After creation of the Fragments inside an Activity, we can also pass data to the fragments calling methods in Fragments.

    For example:

        ArticleFragment articleFrag = (ArticleFragment)
                        getSupportFragmentManager().findFragmentById(R.id.article_fragment);
        articleFrag.updateArticleView(position);
    
    0 讨论(0)
  • 2020-11-21 05:33

    the better approach for sending data from activity class to fragment is passing via setter methods. Like

    FragmentClass fragmentClass = new FragmentClass();
    fragmentClass.setMyList(mylist);
    fragmentClass.setMyString(myString);
    fragmentClass.setMyMap(myMap);
    

    and get these data from the class easily.

    0 讨论(0)
  • 2020-11-21 05:34

    If you pass a reference to the (concrete subclass of) fragment into the async task, you can then access the fragment directly.

    Some ways of passing the fragment reference into the async task:

    • If your async task is a fully fledged class (class FooTask extends AsyncTask), then pass your fragment into the constructor.
    • If your async task is an inner class, just declare a final Fragment variable in the scope the async task is defined, or as a field of the outer class. You'll be able to access that from the inner class.
    0 讨论(0)
  • 2020-11-21 05:34

    Very old post, still I dare to add a little explanation that would had been helpful for me.

    Technically you can directly set members of any type in a fragment from activity.
    So why Bundle?
    The reason is very simple - Bundle provides uniform way to handle:
    -- creating/opening fragment
    -- reconfiguration (screen rotation) - just add initial/updated bundle to outState in onSaveInstanceState()
    -- app restoration after being garbage collected in background (as with reconfiguration).

    You can (if you like experiments) create a workaround in simple situations but Bundle-approach just doesn't see difference between one fragment and one thousand on a backstack - it stays simple and straightforward.
    That's why the answer by @Elenasys is the most elegant and universal solution.
    And that's why the answer given by @Martin has pitfalls

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