Android: How to call getActivity () in OnItemClickListener ()?

I am trying to call getActivity () in 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 created as:

 ViewTest editTest = new ViewTest(this); 

But I get an error message that I can’t fix:

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

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

+8
java android casting onitemclick main-activity
source share
2 answers

You can only use getActivity inside the Fragment class or one of them. If your onItemClickListener is in Activity , use MainActivity.this

+25
source share

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

how

 Context c = this; c.makeResultsbarVisible(); 
0
source share

All Articles