Yar
Yar

Reputation: 7457

adding a fragment to existing ViewGroup, programmatically

I am trying to add a new fragment to current ViewGroup without creating a <fragment> in my main layout, so I did these: created a new java class as a Fragment subclass and also created its layout "R.layout.fraglayout":

public class FragOne extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fraglayout, container, false);
    }
}

now as API's guide said I should add this new fragment to the ViewGroup, so I did this using FragmentTransaction and added it to main_activity's onCreate:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //adding the fragment
    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();

    FragOne newFrag = new FragOne();
    ft.add(R.layout.activity_main, newFrag);
    ft.commit();

    setContentView(R.layout.activity_main);
}

the code is not working and here is my question: The documentation said I should add my fragment to the current "ViewGroup" by I guess I'm adding it to the Layout. Are those same? If not, what is the ViewGoup id then?

Upvotes: 1

Views: 806

Answers (1)

joao2fast4u
joao2fast4u

Reputation: 6892

The ViewGroup id is, for example, the id of a FrameLayout in your Activity layout, R.layout.activity_main.

When using transaction.add(). pass the FrameLayout id as first parameter.

One more thing, call setContentView() right after super.onCreate(savedInstanceState); and only then load your Fragment. Like this:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//adding the fragment
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();

FragOne newFrag = new FragOne();
ft.add(R.id.myContainerFrameLayout, newFrag);
ft.commit();

}

Upvotes: 2

Related Questions