Search code examples
androidandroid-dialogfragment

passing argument to DialogFragment


I need to pass some variables to DialogFragment, so I can perform an action. Eclipse suggests that I should use

Fragment#setArguments(Bundle)

But I don't know how to use this function. How can I use it to pass variables to my dialog?


Solution

  • Using newInstance

    public static MyDialogFragment newInstance(int num) {
        MyDialogFragment f = new MyDialogFragment();
    
        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);
    
        return f;
    }
    

    And get the Args like this

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments().getInt("num");
        ...
    }
    

    See the full example here
    http://developer.android.com/reference/android/app/DialogFragment.html