安卓Android Context类实例详解
1.例如下面的代码片段,Toast类的第一个参数接受一个Context对象:
@Override
protectedDialogonCreateDialog(intid){
switch(id){
case0:
Builderbuilder=newAlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_launcher);
builder.setTitle("Thisisadialogwithsomesimpletext...");
builder.setPositiveButton("OK",
newDialogInterface.OnClickListener(){
publicvoidonClick(DialogInterfacedialog,
intwhichButton){
Toast.makeText(getBaseContext(),"OKclicked!",
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel",
newDialogInterface.OnClickListener(){
publicvoidonClick(DialogInterfacedialog,
intwhichButton){
Toast.makeText(getBaseContext(),"Cancelclicked!",
Toast.LENGTH_SHORT).show();
}
});
builder.setMultiChoiceItems(items,itemsChecked,
newDialogInterface.OnMultiChoiceClickListener(){
publicvoidonClick(DialogInterfacedialog,intwhich,
booleanisChecked){
Toast.makeText(
getBaseContext(),
items[which]
+(isChecked?"checked!"
:"unchecked!"),
Toast.LENGTH_SHORT).show();
}
});
returnbuilder.create();
}
returnnull;
}
@Override
protectedDialogonCreateDialog(intid){
switch(id){
case0:
Builderbuilder=newAlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_launcher);
builder.setTitle("Thisisadialogwithsomesimpletext...");
builder.setPositiveButton("OK",
newDialogInterface.OnClickListener(){
publicvoidonClick(DialogInterfacedialog,
intwhichButton){
Toast.makeText(getBaseContext(),"OKclicked!",
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel",
newDialogInterface.OnClickListener(){
publicvoidonClick(DialogInterfacedialog,
intwhichButton){
Toast.makeText(getBaseContext(),"Cancelclicked!",
Toast.LENGTH_SHORT).show();
}
});
builder.setMultiChoiceItems(items,itemsChecked,
newDialogInterface.OnMultiChoiceClickListener(){
publicvoidonClick(DialogInterfacedialog,intwhich,
booleanisChecked){
Toast.makeText(
getBaseContext(),
items[which]
+(isChecked?"checked!"
:"unchecked!"),
Toast.LENGTH_SHORT).show();
}
});
returnbuilder.create();
}
returnnull;
}
然而,Toast类并没有直接用在Activity中,它被用在了AlertDialog类中。所以,这里需要通过getBaseContext()方法获取一个Context类的实例。
2.在Activity中动态地创建一个视图的时候也会遇见Context。
例如,如果想通过硬编码动态地创建一个TextView:
TextViewtv=newTextView(this); TextViewtv=newTextView(this);
TextView的构造器接受一个Context对象,因为Activity类是Context类的子类,所以可以用this关键字来代替这个Conext对象。
提示:
使用this动态地创建视图,例如TextView、Button,存在一个潜在的风险——内存泄漏。所以,尽可能地使用getApplicationContext()方法替代this。