call method from fragment to Activity

前端 未结 4 2012
孤城傲影
孤城傲影 2021-01-26 06:53

hello i have activity and i call many fragment based on my application business i need to call method from fragment in activity i searched in the internet but i cannot find the

4条回答
  •  后悔当初
    2021-01-26 07:24

    You can Broadcast Intent from the Fragment to activity after you get the bundle

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        Intent intent = new Intent("key_to_identify_the_broadcast");
        Bundle bundle = new Bundle();
        bundle.putString("edttext", json.toString());
        intent.putExtra("bundle_key_for_intent", bundle);
        context.sendBroadcast(intent);
    }
    

    and then you can receive the bundle in your Activity by using the BroadcastReceiver class

    private final BroadcastReceiver mHandleMessageReceiver = new 
    BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = 
                intent.getExtras().getBundle("bundle_key_for_intent");
                if(bundle!=null){
                    String edttext = bundle.getString("edttext");
                }
                //you can call any of your methods for using this bundle for your use case
        }
    };
    

    in onCreate() of your Activity you need to register the broadcast receiver first otherwise this broadcast receiver will not be triggered

    IntentFilter filter = new IntentFilter("key_to_identify_the_broadcast");
    getActivity().getApplicationContext().
                   registerReceiver(mHandleMessageReceiver, filter);
    

    Finally you can unregister the receiver to avoid any exceptions

    @Override
    public void onDestroy() {
        try {
    
             getActivity().getApplicationContext().
                 unregisterReceiver(mHandleMessageReceiver);
    
        } catch (Exception e) {
            Log.e("UnRegister Error", "> " + e.getMessage());
        }
        super.onDestroy();
    }
    

    You can create separate broadcast receivers in all of your fragments and use the same broadcast to broadcast the data to your Activity. You can also use different keys for different fragments and then broadcast using particular key for particular fragment.

提交回复
热议问题