ybakos
ybakos

Reputation: 8630

What's the difference between passing this vs. ClassName.this from an event handler when passed to Intent constructor?

In the earlier Android Programming Tutorial, page 192, we see an implementation of LunchList#onOptionsItemSelected. Within this implementation we see two Intents passed to startActivity: one whose constructor is passed LunchList.this, the other whose constructor is passed this.

What's the difference?

See lines 78 - 91 here. Note how onOptionsItemSelected is not declared within an inner class.

In Android/Java does the value of this change within the context of event handlers or function binding via reflection? Could both Intent instances be passed this?

Upvotes: 8

Views: 3802

Answers (3)

Calvin
Calvin

Reputation: 644

For this example it will make no difference as in either condition the class that will start the activity will remain same. First parameter of the Intent refers to the context of the class from where the activity will be launched and from where the bundle data will be passed.

Upvotes: 1

JimN
JimN

Reputation: 3150

In Java, this refers to the containing class, and ClassName.this refers to the first containing class whose name is ClassName. Event handlers are typically written as anonymous, inner classes, so if you want to refer to the event handler's containing class (and not the event handler's class), you need to specify ContainingClass.this, not this.

Reference: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.4

Upvotes: 11

Nishant
Nishant

Reputation: 32232

When you are creating an Intent inside an Inner Class use ClassName.this(here className must be the Activity class Name) and if creating Intent inside an Activity class you can use this.

Upvotes: 3

Related Questions