Sebastian Delgado
Sebastian Delgado

Reputation: 725

How to open or launch a Fragment from another Activity?

from the adapter of a RecyclerView which is contained in an Activity, i'm trying to launch a fragment when an element of the RecyclerView is pressed, this is my code right now :

@Override
public void onClick(View v) {
    Intent intent;

    int position = getAdapterPosition();

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    String onoff = preferences.getString("it's", "");

    if (onoff.equalsIgnoreCase("on")) {
        if (position == 0) {

            CategoriesRecyclerView.fragSubreddit = "aww";

            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

        if (position == 1) {

            CategoriesRecyclerView.fragSubreddit = "food";

            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

        if (position == 2) {

            CategoriesRecyclerView.fragSubreddit = "funny";

            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

        if (position == 3) {

            CategoriesRecyclerView.fragSubreddit = "gaming";

            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

    } else if (onoff.equalsIgnoreCase("off")) {

        if (position == 0) {

            CategoriesRecyclerView.fragSubreddit = "gaming";
            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

        if (position == 1) {

            CategoriesRecyclerView.fragSubreddit = "funny";
            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

        if (position == 2) {

            CategoriesRecyclerView.fragSubreddit = "food";
            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }

        if (position == 3) {

            CategoriesRecyclerView.fragSubreddit = "aww";
            intent = new Intent(context, MainFragment.class);
            context.startActivity(intent);
        }
    }
}

I Tested it launching some "testing activities" that i created, so i know that everything but the fragment launching works fine.

The error is here :

intent = new Intent(context, MainFragment.class);
context.startActivity(intent);

I'm launching the Fragment as it was an Activity, so when i run the app it crashes and tells me to declare the MainFragment as an activity in my manifest.

How can i launch that Fragment from my Activity?

Thanks very much.

Upvotes: 4

Views: 22650

Answers (3)

Skizo-ozᴉʞS ツ
Skizo-ozᴉʞS ツ

Reputation: 20616

You cannot start a Fragment with Intents so the method that I recommend to you is :

Fragment mFragment = null;
mFragment = new MainFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();

For more information see Fragments Transactions documents

Upvotes: 3

DragonFire
DragonFire

Reputation: 4082

If you are using a Sections Pager Adapter, the simple thing to do would be using an onclick on image view or button like below:

In your starting activity (from where you want to go) use put extra to send some information to another activity

ivPhotoAlbums.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        // Send The Message Receiver ID & Name
        Intent intent = new Intent(v.getContext(), PhotosActivity.class);
        intent.putExtra("viewpager_position", 1);
        v.getContext().startActivity(intent);

    }
});

In your activity in which you want to land (at the end of your setupViewPager() function) catch that extra and use it as position

int position = 0;
Bundle extras = getIntent().getExtras();
if (extras != null) {
    position = extras.getInt("viewpager_position");
}
viewPager.setCurrentItem(position);

Given the Assumption that your setupViewPager() function looks like below in your destination activity

SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());

adapter.addFragment(new FriendsAlbumsFragment()); //index 0
adapter.addFragment(new MyAlbumsFragment()); //index 1
adapter.addFragment(new AddPhotosFragment()); //index 2

final ViewPager viewPager = findViewById(R.id.l_center_view_pager_view_pager);
viewPager.setAdapter(adapter);

TabLayout tabLayout = findViewById(R.id.l_top_tabs_tabs);

tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_friends_photos);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_my_photos);
tabLayout.getTabAt(2).setIcon(R.drawable.ic_add_photos);

And Your SectionsPagerAdapter class looks like below (separate public class)

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> mFragmentList = new ArrayList<>();

    public SectionsPagerAdapter(FragmentManager fm) {

        super(fm);

    }

    @Override
    public Fragment getItem(int i) {

        return mFragmentList.get(i);
    }

    @Override
    public int getCount() {

        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment) {

        mFragmentList.add(fragment);
    }
}

And your center view pager layout is

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <android.support.v4.view.ViewPager
        android:id="@+id/l_center_view_pager_view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="56dp">

    </android.support.v4.view.ViewPager>

</merge>

Included in another file like this (or not included - in my case it was included)

<include layout="@layout/layout_center_viewpager" />

This will take you right from an activity to a fragment (in another activity) or from a fragment in one activity to a fragment in another activity...

Upvotes: 0

Olkunmustafa
Olkunmustafa

Reputation: 3201

You can not start a Fragment using Intents. Intents provide a communication between activities.

If you want to launch a Fragment from other Fragment you have two options.

1- You can replace or add a new fragment.

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction
                .replace( R.id.content_frame, fragment )
                .addToBackStack( null )
                .commit();

In this case The activity has two fragments.

2- You can launch a new Activity that contains a Fragment.

Upvotes: 1

Related Questions