Calling fragment from a list adapter

zoya ali picture zoya ali · Feb 9, 2013 · Viewed 15.2k times · Source

I am using sliding menu/drawer pattern in my app. So the main activity has a leftView which is a ListFragment named topicsFragment() which loads set of topic items. When an item/topic is clicked it replaces the fragment on main view by calling the FeedsFragment(tag). FeedsFragment uses arraylist adapter to load the feeds which has various clickable items in each list item. I want to fetch another instance on the feedsFragment(tag) when an item is clicked within a list item.

    holder.contextView= (TextView) newsView.findViewById(R.id.arcHeader);
    if (item.hasArc()) {
        holder.contextView.setVisibility(View.VISIBLE);
        String arc;
        try {
            arc=item.getarc();
            holder.contextView.setText(arc);

            holder.contextView.setOnClickListener(new View.OnClickListener() {

                //currently it loads a class
                @Override
                public void onClick(View v) { 
                   Intent i = new Intent(context, SomeClass.class); 
                   i.putExtra("tag", arc);
                   context.startActivity(i);
                }
            });
        } catch (JSONException e) {

            e.printStackTrace();
        }

    } else {
        holder.contextView.setVisibility(View.GONE);
    }

Currently it loads a new class. I want to define a fragment and then pass to main activity to replace with the current view but I cant use getSupportFragmentManager() inside an adapter class but only in a fragment or fragment activity. What should be an alternative to sweeping in a fragment from an adapter?

Answer

Justin Vartanian picture Justin Vartanian · Feb 9, 2013

What I did was create this method in my main activity and just called it from other classes to change the fragment:

public void switchContent(Fragment fragment) {
        mContent = fragment;
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment).commit();

        slidemenu.showContent();

    }