Search code examples
androidandroid-fragmentsfragmenttransaction

Fragment transaction add/replace not working from within a fragment


I have been breaking my head over this issue from a few days. Nothing seems to be working.

The following is the code where the fragment resides.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:theme="@style/Theme.Breathe"
    tools:context=".MainActivity">

    <fragment
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:id="@+id/mainFrag"
        android:tag="fragment"
        class="com.sneaky.example.HomeFrag"/>

</FrameLayout>

The following is the code from mainactivity where the first transaction happens. The below code executes and functions as expected.

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
    Fragment fragment = new HomeFrag();
    fragmentTransaction.add(R.id.mainFrag,fragment);
    fragmentTransaction.commit();

The following is the code from HomeFrag that we added in the previous snippet. This code seems to be doing nothing. Clicking the card has no effect. CardView onClick seems to be working fine because Log.d and toasts execute onClick.

card.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                
                    FragmentTransaction transaction = getFragmentManager().beginTransaction();
                    Fragment newFragment = new FragSec();
                    transaction.replace(R.id.mainFrag, newFragment);
                    transaction.addToBackStack(null);
                    transaction.commit();
                
        }
    });

Any help would be really appreciated. :D


Solution

  • If you already add HomeFrag by code, Try to change XML to this without declare <fragment/> inside

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:theme="@style/Theme.Breathe"
        android:id="@+id/mainFrag"
        tools:context=".MainActivity"/>