2014-01-27 77 views
0

更換片段我有一個問題,我被困在如何實現以下結構:刪除/從活動

class A extends FragmentActivity{ 
    //In this I click a button which loads a fragment say class B 
} 

class B extends Fragment implments Interface{ 
    //This has a button which opens up an activity of list view say class C 

    function replaceFragment(){ 
     try{ 
     FragmentManager fm = B.this.getFragmentManager(); 
     fm.beginTransaction().replace(R.id.main_frame, new D()).commit(); 
    }catch(Exception e){ 
     Log.v("error",""+e.getMessage()); 
    } 
    } 
} 

class C extends Activity{ 
    //It has an async task which loads something when the list view is clicked 
    //The async task onPostExecute calls back the class B interface function 

    onPostExecute(){ 
    callback.replaceFragment(); 
    } 
} 

現在,當接口函數被調用我要替換的B片段另一個片段說D有它自己的佈局。任何人都可以幫助我提出這個建議或解決我遇到的問題嗎?

另一種我認爲不是調用回調函數的方法我會重新開始類A,並在加載時將片段更改爲D,但之後的類A沒有從堆棧中移除,並且當我按回我再次得到類A片段活動,這是一個問題。需要一個解決方案,因爲我在這個問題上陷入困境。

回答

0

當接口函數被調用,您可以用Fragment D取代現有的Fragment如下

Fragment d = new D(); 
fragmentManager.beginTransaction().replace(R.id.frame_container, d).commit(); 

R.id.frame_container1FrameLayout,在那裏你添加/替換您選擇片段

+0

感謝您的回覆,但後來我從C調用接口函數吧?所以,如果我在B中定義回調函數並編寫你給出的代碼,那麼R.id.frame_container將不會被找到,因爲它在A的視圖中不在B. – fastLearner

+0

我在函數定義中放入了一些代碼。請看看,讓我知道如果我在我的代碼中做錯了事情,當我試圖替換片段時,它總是進入catch部分。 – fastLearner

+0

你有什麼異常? –

0

你可以嘗試調用replace的ID在你的界面中回調。我認爲這應該很好。

+0

我已經在我的問題中提出了一些代碼,我試過了,但在替換片段時它總是進入catch部分。請讓我知道如果我做錯了什麼。 – fastLearner