2013-09-05 22 views
5

Tại sao sau khi thay đổi các đoạn từ trang đầu tiên (pageNews) sang trang thứ hai (pageViewFromWeb) "findFragmentById" trả về tham chiếu đến đoạn đầu tiên (pageNews)?Tại sao findFragmentById trả về đoạn cũ trước khi cuộc gọi thay thế FragmentLayout?

bố trí:

<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> 

mã:

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); 
    ... 
} 
+3

Vui lòng xem tài liệu về ['FragmentTransaction'] (http://developer.android.com/reference/android/app/FragmentTransaction.html# commit()). commit() chỉ đơn giản là lịch trình giao dịch để hoàn thành một thời gian trong tương lai và không chặn hoặc chạy khác ngay lập tức. Bạn có thể xem xét ['FragmentManager.executePendingTransactions()'] (http://developer.android.com/reference/android/app/FragmentManager.html#executePendingTransactions()). – JuniKim

+0

Cảm ơn! Đó là công việc. –

Trả lời

2

của nó vì replace() không thực hiện ngay lập tức, nhưng FragmentTransaction được lên kế hoạch. Khi bạn findFragmentById() ngay sau khi thay thế các đoạn, chúng chưa được thay thế ...