Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why findFragmentById returns the old fragment was in before the call to replace FragmentLayout?

Why after changing fragments from the first(pageNews) to the second(pageViewFromWeb) "findFragmentById" returns a reference to the first(pageNews) fragment?

layout:

<RelativeLayout 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"
    tools:context=".MainActivity"
    android:paddingTop="10dp"
    android:background="#000">

    <FrameLayout
        android:id="@+id/frgmCont"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#000000">
    </FrameLayout>

</RelativeLayout>

code:

   fTrans = getSupportFragmentManager().beginTransaction();
   fTrans.add(R.id.frgmCont, pageNews);
   ....
   ....    
   public void selectNews(String news_id) {
   // Toast.makeText(this, news_id, Toast.LENGTH_SHORT).show();
    fTrans = getSupportFragmentManager().beginTransaction();
    fTrans.replace(R.id.frgmCont, pageViewFromWeb);
    fTrans.commit();
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frgmCont);
    ...
}
like image 673
happy_yar Avatar asked Oct 22 '22 01:10

happy_yar


1 Answers

Its because replace() does not execute immediately, but the FragmentTransaction is scheduled. When you findFragmentById() immediately after replacing fragments, they are not replaced yet...

like image 174
hendrix Avatar answered Oct 24 '22 05:10

hendrix