passing context as argument of DialogFragment

无人久伴 提交于 2019-12-02 18:00:48

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.

For more information, read the Fragment documentation

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    context=activity;
}

Need to use onAttach method : for dialog Fragment

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);
}
anand krish

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!