Android: How to pass arguments/parameters to DialogFragment?

In this short post I will show you how to dynamically provide arguments to DialogFragment from another Fragment or Activity.

newInstance

Let’s create static public newInstance method in your DialogFragment.

    static public TestDialogFragment newInstance(String testStringArg) {
        TestDialogFragment f = new TestDialogFragment();

        // Add provided argument to Bundles
        Bundle args = new Bundle();
        args.putString("testStringArgKey", testStringArg);
        f.setArguments(args);
        return f;
    }

And next in the onCreateDialog method just get this argument value like in the code below.

    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        ...
        final String testStringArgValue = getArguments().getString("testStringArgKey");
        ...
    }

Finally

Now you can pass arguments from your entry Fragment or Activity.

DialogFragment newFragment = TestDialogFragment.newInstance("BigDataETL is awesome!");

If you enjoyed this post please add the comment below or share this post on your Facebook, Twitter, LinkedIn or another social media webpage.
Thanks in advanced!

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu