Search code examples
androidandroid-fragmentsandroid-listfragment

Replacing fragments


I want to replace fragment B1 with fragment B2 after selecting listFragment A items.

@Override
public void onListItemClick(ListView l, View v, int position, long id) {

    Integer Position = position;
    WebViewerFragment fragment = (WebViewerFragment) getFragmentManager()
            .findFragmentById(R.id.detailFragment);
    if (Position.equals(0)) {
        FragmentManager fm = getFragmentManager();
        WebViewerFragment newFragment = new WebViewerFragment();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.detailFragment, newFragment);
        ft.addToBackStack("android");
        ft.commit();
    } else if (Position.equals(1)) {
        FragmentManager fms = getFragmentManager();
        WebViewerFragment_II newFragments = new WebViewerFragment_II();
        FragmentTransaction fts = fms.beginTransaction();
        fts.replace(R.id.detailFragment, newFragments);
        fts.addToBackStack("google");

        fts.commit();
    } 
}

It replaces just for once and after selecting item 1 (position 0) again application crashes.


Solution

  • When you call the method replace(int, Fragment) of FragmentTransaction, the int must be the id of the container in which you want to put your new Fragment and in which were the previous one. Typically, it's a FrameLayout.
    You can't replace a Fragment which has been set with XML.