Android - getTargetFragment and setTargetFragment - What are they used for

前端 未结 3 426
夕颜
夕颜 2020-11-29 06:06

I tried searching but i\'m still a little lost. I usually do fragment to fragment communication through an Activity via interfaces or a BroadcastReceiver

3条回答
  •  广开言路
    2020-11-29 06:32

    i finally found out how to use setTarget in a fragment and wanted to share. its quite useful when you want to communicate from fragment to fragment.

    here is an example: let's say you wanted to show a dialog and when it closes you want to do some action.

    so in your fragment1 that will use the dialog you could do this:

    myDialogFragment.setTargetFragment(fragment1, myDialogFragment.REQ_CODE);
    

    and in your fragment that called the dialog you would need to override onActivityResult like this:

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == CoDDialogFragment.REQ_CODE)
            exit(); //or whatever you want to do here
    }
    

    and in the myDialogFragment you could do this:

    TellTargetYouGotResults(REQ_CODE);
    
    //...
    private void TellTargetYouGotResults(int code) {
        Fragment targetFragment = getTargetFragment(); // fragment1 in our case
        if (targetFragment != null) {
            targetFragment.onActivityResult(getTargetRequestCode(), code, null);
        }
    }
    

    where REQ_CODE can be any int of course . Very useful for fragment to fragment communication. but i still prefer event bus as sometimes after sending data to a target its view might have already been destroyed (incase its a fragment) and then if you try to update the view in onActivityResult you'll get a crash. so i'd say its useful to just pass data along but not update the UI unless you've done a 'add' fragment transaction and not a replace (which destroys the view but keeps state).

提交回复
热议问题