Aharon Manne
Aharon Manne

Reputation: 712

Adding Fragments Dynamically

I am thoroughly confused. According to this and this and numerous other sources, both on SO and elsewhere, I should be able to do the following:

import android.os.Bundle;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.view.Menu;

public class MainScreenActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_screen);
    MainRightFragment mrf = new MainRightFragment();
    RecommendedFragment rf = new RecommendedFragment();

    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.add(R.id.main_search_boxes, mrf, "fragmentright");
    ft.add(R.id.main_left_side, rf, "fragmentreccomend");
}

}

The R.id references point to FrameLayout objects in my .xml file. Why am I still getting the "The method add(int, Fragment, String) in the type FragmentTransaction is not applicable for the arguments (int, RecommendedFragment, String)" error message?

Upvotes: 8

Views: 21754

Answers (4)

Bruno Freitas
Bruno Freitas

Reputation: 343

To add fragments at Runtime you need to extends your main activity from: android.support.v4.app.FragmentActivity

And you need to use the classes FragmentManager and FragmentTransaction from android.support.v4.app package, instead of android.app.

Also, when you get the FragmentManager use the method getSupportFragmentManager(). See the code below:

FragmentManager fm = getSupportFragmentManager();

FragmentTop fragTop = new FragmentTop();
FragmentLeft fragLeft = new FragmentLeft();

FragmentTransaction ft = fm.beginTransaction();

ft.add(R.id.fragTop, fragTop);
ft.add(R.id.fragLeft, fragLeft);

ft.commit();

Reference: http://developer.android.com/intl/pt-br/training/basics/fragments/fragment-ui.html

Upvotes: 3

Aharon Manne
Aharon Manne

Reputation: 712

This is more of a capitulation than an answer, but I was able to get what I wanted using FragmentActivity/support.v4.app. I still don't understand why the references I cited above seem to say that it is possible to use the .add(...) function with the modern API.
Both harsha.cs and Damien point to FragmentActivity, so until someone explains why it is necessary to use the backwards compatibility API, I will give both points, and hold off on checking an answer.

Upvotes: 1

harsha.cs
harsha.cs

Reputation: 132

Try this.

FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(FragmentA.this.getParent().getID(), mNewFragment,"your frame name");
ft.addToBackStack(null);
ft.commit();

Upvotes: 0

Damien R.
Damien R.

Reputation: 3373

Your MainScreenActivity should extends FragmentActivity and not just Activity. Also, don't forget to call ft.commit();

Upvotes: 8

Related Questions