Tutorial 21/22 : This.GestureDetector keyword clarification

+1 Adrian Xu · January 13, 2016
Hi All,

First of all, as a chemist, I love these tutorials and this is a great community. 

On to my question

In the tutorial specified we have the following piece of code under the OnCreate() method in the MainActivity class:
this.gestureDetector= new GestureDetectorCompat(this,this);

I've done some work on the keyword, and I'd like to ask whether this could be expanded to:
MainActivity.gestureDetector= new GestureDetectorCompat(MainActivity,MainActivity);

If so, are we saying that the gestureDetector object for this instance of MainActivity is the same as creating object of class GestureDetectorCompat with arguments of MainActivity, MainActivity?

I thought this could only be used to refer to variables outside the class? Or to pass info from overloaded constructors to other ones.

And what's up with the arguments? I thought GestureDetectorCompat takes a Context and a listener?

I've gone through all the other posts on the subject but am still confused, so any related advice would be appreciated.

Thanks all.

Post a Reply

Replies

Oldest  Newest  Rating
0 Gary Whitney · January 13, 2016
this is used to refer to the object where the word this appears.
You are right. Here it is used as a shorthand for MainActivity.

The first this, at the beginning of the statement, is not necessary because gestureDetector was declared at the class level.


Given that the activity was declared as
public class MainActivity extends ActionBarActivity implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener{
it has to implement the methods from those interfaces, which is what the rest of the code does.
My point is the activity is both the context and the interface. So the two parameters this and this are both accurate.
  • 1

Java / Android Development

107,013 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator