what context should i use AlertDialog.Builder in?

2019-04-06 12:56发布

Could anyone please explain what context should i use the AlertDialog.Builder class? I am new to android app development and I frankly don't understand which context to use when?

Say, I want to create an object for AlertDialog.Builder class -

AlertDialog.Builder ab = new AlertDialog.Builder();
ab.setMessage("Test");

ab.show();

What context should I use it in? Does it differ if I use the Alert Dialog onCreate or OnClickListener or in the handler of any such event?

3条回答
我想做一个坏孩纸
2楼-- · 2019-04-06 13:27

You should use the context of the Activity that it's executed from. In other words, just use YourNameOfActivity.this as context.

查看更多
该账号已被封号
3楼-- · 2019-04-06 13:37
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Test")
  .show;

(or) if u want (yes,no) button means use this

AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Are you sure you want to exit?")
  .setPositiveButton("Yes", dialogClickListener)
  .setNegativeButton("No", dialogClickListener)
  .show();
查看更多
贼婆χ
4楼-- · 2019-04-06 13:41

In the first version of my app I made the mistake of not using onCreateDialog and instead built and showed the dialogs myself. If you do it yourself you have to take care of things like dismissing the dialog before the activity is finish()ed otherwise a window will leak.

I would override onCreateDialog in your activity and return ab.create() (not show()). onCreateDialog will then handle showing the dialog and you'll just have to call showDialog(id).

查看更多
登录 后发表回答