java
java

Reputation: 1165

getSupportFragmentManager() - undefined for the type Context

How do I solve the following problem when instanciationg a Fragment class

holder.infoView.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View v) {
       Fragment infoFragment = new ExampleFragment();
                    infoFragment.show(context.getSupportFragmentManager(), "settings");

     ....

the actual class (MySimpleArrayAdapter) which this code is part of - does not extend FragmentActivity - but takes a context (via the constructor) from another class that extends that class.

All the same I cannot use the context such as

 infoFragment.show(context.getSupportFragmentManager(), "settings");

I get the error:the method getSupportFragmentManager() is undefined for the type Context.

Is there a simple solution to this issue?

Upvotes: 1

Views: 3705

Answers (2)

Phocacius
Phocacius

Reputation: 1148

You have two options:

  • First, you can call getSupportFragmentManager()in your FragmentActivity, save it as a variable and pass it to your Adapter as a second constructor parameter.
  • When you are sure that the Context Object is always derived from the FragmentActivity class, you can cast the Context object to FragmentActivity. Then you can call method, like ((FragmentActivity) context).getSupportFragmentManager().

I hope that helped!

Upvotes: 7

user468311
user468311

Reputation:

I believe this method is only defined for Activity class. Also if you decide to pass Activity instance to your adapter, that's not a very good idea. Consider using interfaces with Observer pattern to communicate between Adapter and Activity.

Upvotes: 0

Related Questions