kovacs lorand
kovacs lorand

Reputation: 906

How to reference the MainActivity from an OnClickListener?

This is in the MainActivity:

    imgModeContrastLeft.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               ImagePair imp = new ImagePair();
               String objId = "sMfSYvBxmX";
               imp.downloadImagePairInBackground(this, objId);
           }        
    });

But the this is not the MainActivity. How do I reference the main activity in the OnClickListener?

Upvotes: 0

Views: 232

Answers (5)

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95569

As has been noted in one of the other answers, you can qualify this with a class name to reference a specific outer class from within an inner class. However, this syntax is somewhat obscure, and so I would recommend the more explicit (if also more verbose) approach of simply assigning to a local:

 final MainActivity mainActivity = this;
 imgModeContrastLeft.setOnClickListener(...); // reference "mainActivity"

Upvotes: 0

Sarthak Mittal
Sarthak Mittal

Reputation: 6104

First of all, Remember that a whole InnerClass is tied to every single object of the outside class, subject to the condition that InnerClass ain't static and you have created an object of InnerClass too.

Now, whenever you need access to the reference of the object that invoked the InnerClass the Syntax is:

OuterClassName.this;

Upvotes: 1

codeMagic
codeMagic

Reputation: 44571

v.getContext() here is the "best" way

public void onClick(View v) {
    ImagePair imp = new ImagePair();
     String objId = "sMfSYvBxmX";
     imp.downloadImagePairInBackground(v.getContext(), objId);
 }        

It will make it more "portable" so if you move, decide to reuse the code in another class, or change the class name, you don't need to change it.

The way you have it, this is referring to the inner-class and not the Activity Context

Upvotes: 2

Giacomo De Bacco
Giacomo De Bacco

Reputation: 723

That's the right code:

imgModeContrastLeft.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               ImagePair imp = new ImagePair();
               String objId = "sMfSYvBxmX";
               imp.downloadImagePairInBackground(MainActivity.this, objId);
           }        
    });

Upvotes: 0

tyczj
tyczj

Reputation: 73916

you can do MainActivity.this to get the MainActivity context

Upvotes: 4

Related Questions