Send data from activity to fragment in Android

前端 未结 20 2790
悲哀的现实
悲哀的现实 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条回答
  •  Happy的楠姐
    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);
    

提交回复
热议问题