1.例如下面的代码片段,Toast类的第一个参数接受一个Context对象:
@Override protected Dialog onCreateDialog(int id) { switch (id) { case 0: Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.ic_launcher); builder.setTitle("This is a dialog with some simple text..."); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), "OK clicked!", Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), "Cancel clicked!", Toast.LENGTH_SHORT).show(); } }); builder.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { Toast.makeText( getBaseContext(), items[which] + (isChecked ? " checked!" : " unchecked!"), Toast.LENGTH_SHORT).show(); } }); return builder.create(); } return null; } @Override protected Dialog onCreateDialog(int id) { switch (id) { case 0: Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.ic_launcher); builder.setTitle("This is a dialog with some simple text..."); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), "OK clicked!", Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), "Cancel clicked!", Toast.LENGTH_SHORT).show(); } }); builder.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { Toast.makeText( getBaseContext(), items[which] + (isChecked ? " checked!" : " unchecked!"), Toast.LENGTH_SHORT).show(); } }); return builder.create(); } return null; }
然而,Toast类并没有直接用在Activity中,它被用在了AlertDialog类中。所以,这里需要通过getBaseContext()方法获取一个Context类的实例。
2.在Activity中动态地创建一个视图的时候也会遇见Context。
例如,如果想通过硬编码动态地创建一个TextView:
TextView tv = new TextView(this); TextView tv = new TextView(this);
TextView的构造器接受一个Context对象,因为Activity类是Context类的子类,所以可以用this关键字来代替这个Conext对象。
提示:
使用this动态地创建视图,例如TextView、Button,存在一个潜在的风险——内存泄漏。所以,尽可能地使用getApplicationContext()方法替代this。