Home > OS >  Call registerForActivityResult from non-Fragment/Activity class
Call registerForActivityResult from non-Fragment/Activity class

Time:10-01

I want to call registerForActivityResult from a Java class other than my Fragment. Is it possible to do that?

Here you can see an example of what I mean:

public class Hello
{
    private ActivityResultLauncher<String[]> mMultipleActivityResultLauncher =
        registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), isGranted ->{
            
        });
}

CodePudding user response:

You need to pass the Activity/Fragment instance to the class, and call registerForActivityResult on that.

For example, based on your code (for an Activity, just replace all the instances of Fragment with Activity):

public class Hello {
    private Fragment fragment;
    private ActivityResultLauncher<String[]> mMultipleActivityResultLauncher;

    public Hello(Fragment fragment) {
        this.fragment = fragment;
        this.mMultipleActivityResultLauncher = fragment.registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(), isGranted -> {

        });
    }
}
  • Related