Friday, September 12, 2014

Context Object

Activity class is a subclass of Context, you can use the this keyword to represent the Context object.

Instances of the Context class are often used to provide references to your application.

Context 
    ^
    |
    |
Activity

When creating a view dynamically in an activity.
The constructor for the TextView class takes a Context object.

TextView tv = new TextView(this);


Because the Toast() class is not used directly in the activity (it is used within the AlertDialog class), you need to return an instance of the Context class by using the getBaseContext() method.

.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
Toast.makeText(getBaseContext(),
"OK clicked!", Toast.LENGTH_SHORT)
.show();
}


No comments:

Post a Comment