Android: How to call getActivity() in OnItemClickListener()?
Asked Answered
P

2

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.

Polly answered 12/12, 2013 at 10:21 Comment(6)
post your full class code if possible... are you using in Fragment?Charil
Is this an activity or a fragment?Janitajanith
its in a class that is instantiated in a fragmentPolly
can you post your outer(main) class declaration and inner class declaration? I mean is your inner class is static?Charil
you need to add more info to your question to get help...Charil
is ViewTest class inner class of your Fragment class?Charil
V
34

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

Verina answered 12/12, 2013 at 10:24 Comment(1)
Great solution! What exactly gives me MainActivity.this when called from Listener inside MainActivity class, current instance of MainActivity??Distinct
S
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();
Shelbashelbi answered 12/12, 2013 at 10:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.