10

I am trying to call getActivity() in the OnItemClickListener:

class ViewTest{ //called in a fragment
setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int p, long i) {
                ((MainActivity) getActivity()).makeResultsbarVisible();
...
            }

        });

}

In the fragment, the class is instantiated as:

ViewTest editTest = new ViewTest(this);

But I get an error that I cannot fix:

The method getActivity() is undefined for the type new AdapterView.OnItemClickListener(){}

How can I call getActivity inside onItemClick()? Thanks.

user2212461
  • 3,105
  • 8
  • 49
  • 87

2 Answers2

34

You can only use getActivity inside a Fragment class or one extending it. If your onItemClickListener is in an Activity use MainActivity.this

Apoorv
  • 13,470
  • 4
  • 27
  • 33
  • Great solution! What exactly gives me MainActivity.this when called from Listener inside MainActivity class, current instance of MainActivity?? – patryk Nov 28 '17 at 23:35
0

Use Class_name.this or define a Context variable. and then call your makeResultsbarVisible() by using Context variable,

Like,

Context c = this;

c.makeResultsbarVisible();
Mitesh Shah
  • 1,729
  • 2
  • 19
  • 37