passing context as argument of DialogFragment

2020-05-18 08:59发布

it's possible to pass a context variable to a DialogFragment?

i've use this code inside dialog for passing a string:

public static ConfirmDialog newInstance( String f) {
    ConfirmDialog d = new ConfirmDialog();

    Bundle args = new Bundle();
    args.putString("FILE_NAME", f);
    d.setArguments(args);

    return d;
}

but i don't find any function like putString for passing context. It's possible to do that?

4条回答
可以哭但决不认输i
2楼-- · 2020-05-18 09:19
@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    context=activity;
}

Need to use onAttach method : for dialog Fragment

查看更多
贼婆χ
3楼-- · 2020-05-18 09:20

onAttach(Activity activity) is now deprecated,

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}


use onAttach(Context context) instead

@Override
public void onAttach(Context context) {
    super.onAttach(context);
}
查看更多
Rolldiameter
4楼-- · 2020-05-18 09:25

Your DialogFragment has a very handy method for getting a Context instance:

getActivity()

Fragment#getActivity() will return the instance of the Activity (which is a Context) that the Fragment is attached to. Use it after the Fragment's onAttach() is called. The below chart illustrates the Fragment lifecycle, as you can see, using getActivity() from onCreate() to onDestroy() should be a valid call.

enter image description here

For more information, read the Fragment documentation

查看更多
狗以群分
5楼-- · 2020-05-18 09:35

use like this:

public class Dialog extends DialogFragment implements OnClickListener {
    public void onClick(View v) {
    switch (v.getId()) {
        case R.id.message: {
            this.startActivity(new Intent(context, Login.class));
                                 //or use getActivity() instead of context
            }
            break;
         }
    }
    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        context=activity;
    }
}
查看更多
登录 后发表回答