2012-12-02 130 views
0

我想在選擇listFragment A項目後用片段B2替換片段B1。替換片段

@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(); 
    } 
} 

它只是替換一次,選擇項目1(位置0)後,應用程序崩潰。

+0

請發送異常的堆棧跟蹤。 – yDelouis

回答

0

當您調用FragmentTransaction的方法replace(int, Fragment)時,int必須是要在其中放置新的Fragment的容器的標識,並且其中前一個爲。通常,這是一個FrameLayout
您無法替換已使用XML設置的Fragment

+0

謝謝。現在應用程序不會崩潰,但addTobackStacK不起作用。當我將'ft.replace'改爲'ft.add'時,它也可以工作。爲什麼? –

+0

我認爲這是一個堆棧,當你點擊後面時,你會刪除頂部的片段。所以,如果你調用replace,你會刪除這個片段,並且什麼都不會保留。如果您調用add,則刪除最後一個片段,然後出現下面的片段。 – yDelouis