Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 413
Aharon Manne Avatar asked Oct 24 '13 08:10

Aharon Manne


2 Answers

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

like image 159
Damien R. Avatar answered Sep 30 '22 18:09

Damien R.


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

like image 35
Bruno Freitas Avatar answered Sep 30 '22 19:09

Bruno Freitas