1. For example, the following code fragment, the first parameter of the Toast class accepts a context object:
@Override protected Dialog oncreatedialog (int id) {switch (ID) {case 0:builder Builder = new Alertdialog.bui
Lder (this);
Builder.seticon (R.drawable.ic_launcher);
Builder.settitle ("This are 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 dial
OG, int whichbutton) {Toast.maketext (Getbasecontext (), "Cancel clicked!", Toast.length_short). Show ();
}
}); Builder.setmultichoiceitems (items, itemschecked, new Dialoginterface.onmultichoiceclicklistener () {public void onCl
Ick (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.builde
R (this);
Builder.seticon (R.drawable.ic_launcher);
Builder.settitle ("This are 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 dialo
g, int whichbutton) {Toast.maketext (Getbasecontext (), "Cancel clicked!", Toast.length_short). Show ();
}
}); Builder.setmultichoiceitems (items, itemschecked, new Dialoginterface.onmultichoiceclicklistener () {public void OnCli CK (dialoginterface dialog, int which, Boolean ischecked) {Toast.maketext (Getbasecontext (), Items[which] + (ischecked?)
"Checked!"
: "unchecked!"), Toast.length_short). Show ();
}
});
return Builder.create ();
return null; }
However, the Toast class is not used directly in the activity, and it is used in the Alertdialog class. So, here you need to get an instance of a context class through the Getbasecontext () method.
2. The context is also met when a view is dynamically created in the activity.
For example, if you want to dynamically create a TextView through hard coding:
TextView TV = new TextView (this);
The TextView constructor accepts a context object because the activity class is a subclass of the context class, so you can replace the Conext object with the This keyword.
Tips:
Use this to dynamically create a view, such as TextView, Button, which has a potential risk--a memory leak. So, use the Getapplicationcontext () method as much as possible instead of this.