Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start FragmentTransaction from within ArrayAdapter

I have a ListView with several rows. Each row has a button.

I want the button to start a FragmentTransaction to replace the Fragment that the ListView is in.

However, in the getView() method of the Adapter, this line does not work:

FragmentTransaction t = getContext().getSupportFragmentManager().beginTransaction();

It does not like the context.

Can this be done in this way or does the Transaction have to happen elsewhere?

like image 958
TheLettuceMaster Avatar asked Mar 11 '13 00:03

TheLettuceMaster


3 Answers

First get the context in your Constructor and then try following code,

FragmentTransaction ft = ((FragmentActivity)context).getSupportFragmentManager().beginTransaction();
like image 78
Melbourne Lopes Avatar answered Oct 05 '22 08:10

Melbourne Lopes


getSupportFragmentManager() is only defined for the class FragmentActivity, not for Context. Thus, the compiler can't resolve the call if you try to call it on an object of type Context.

You can use reflection to do this in a safe way. This will always work as long as you pass your FragmentActivity as the Context. Note: FragmentActivity is a subclass of Context, and thus you can pass FragmentActivity wherever you can pass Context.

So use this code instead:

if (getContext() instanceof FragmentActivity) {
    // We can get the fragment manager
    FragmentActivity activity = (FragmentActivity(getContext()));
    FragmentTransaction t = activity.getSupportFragmentManager().beginTransaction();
}
like image 36
Tushar Avatar answered Oct 05 '22 09:10

Tushar


I'd suggest you to pass FragmentManager instance to the Adapter constructor like that:

public class YourAdapter extends...

    private FragmentManage mFragmentManager;        

    public YourAdapter(FragmentManager fm) {
        mFragmentManager = fm;
    }

And use it explicitly:

FragmentTransaction ft = mFragmentManager.beginTransaction();

That should give you posibility to initialize Adapter with either Fragment.getFragmentManager() or FragmentActivity.getSupportFragmentManager() instance, since they are pointed at the same object

like image 37
Mykhailo Gaidai Avatar answered Oct 05 '22 07:10

Mykhailo Gaidai