Siva Natarajan
Siva Natarajan

Reputation: 1429

Adding a Fragment Dynamically inside a view

I have started with this How do I add a Fragment to an Activity with a programmatically created content view

To create and add a Fragment inside an Activity.

But when i tried to add the same fragment inside a dynamic view, it failed.

Can u please address what is the problem behind it.

public class MainActivity extends FragmentActivity {

    private static final int CONTENT_VIEW_ID = 10101010;
    private static final int CONTENT_VIEW_ID1 = 10101011;

    public FragmentManager fm = getSupportFragmentManager();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        View view = new View(this);

        FrameLayout frame = new FrameLayout(this);
        frame.setId(CONTENT_VIEW_ID);
        frame.addView(view,new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        view.setId(CONTENT_VIEW_ID1);
        setContentView(frame);
        if (savedInstanceState == null) {
            Fragment newFragment1 = new DebugExampleTwoFragment();
            FragmentTransaction ft = fm.beginTransaction(); 
            ft.add(CONTENT_VIEW_ID1, newFragment1);
            ft.commit();
        }

public static class DebugExampleTwoFragment extends Fragment {
        public static int count = 0;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View v = new View(getActivity());
            v.setBackgroundColor(Color.RED);
            return v;
        }
    }

It failed with ClassCastException the exact line number is not displayed.

Upvotes: 4

Views: 13183

Answers (1)

Leszek
Leszek

Reputation: 6598

You are probably getting message like this:

java.lang.ClassCastException: android.view.View cannot be cast to android.view.ViewGroup

That's because fragment can be inserted into ViewGroup or something that inherits from ViewGroup. You cannot insert fragment into View. To make your code run change this line:

View view = new View(this);

into ,for example, this:

FrameLayout view = new FrameLayout(this);//FrameLayout inherits from ViewGroup

Upvotes: 4

Related Questions