Atiq
Atiq

Reputation: 14835

How to initialize a fragment from activity?

I have a Main Menu and created a fragment and its layout. Now I can't seems to start fragment when user presses a button on main menu. main menu has its own layout. now is there anyway i could initialize it from a button?

Button bt = (Button)findViewById(R.id.button1);

    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainMenu.this, ExercisesFragment.class));

        }
    });
}

I tried it by this but it gives error saying

Fragment cannot be cast to android.app.Activity

Upvotes: 2

Views: 5067

Answers (3)

AbuQauod
AbuQauod

Reputation: 919

  FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
    ft.add(R.id.main_fragment, your_fragment);
    ft.addToBackStack("ifneeded");
    ft.commit();

Upvotes: 2

marcinj
marcinj

Reputation: 50046

You add fragments using fragment manager:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExercisesFragment fragment = new ExercisesFragment();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();

read more on fragments, start here:

http://developer.android.com/guide/components/fragments.html

Upvotes: 3

Chirag
Chirag

Reputation: 967

You are doing it wrong! Intents are not used to load a fragment. Solution is to use fragment transactions to dynamically load the fragment you wish to bring into focus.

Here is what you need to do:

  1. Have a container for the fragment inside the layout of you activity Example: Assuming the layout resource of my activity is activity_main.xml, I would have a container like so

  2. Follow this guide to create a Fragment

  3. Assuming you already have a fragment setup with name AbcFragment, use fragment transactions to load the fragment into the container that you just created, whenever the user clicks on the button:


    bt.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            getFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment-container, new AbcFragment)
                .commit();
        }

    });

Upvotes: 0

Related Questions