2013-05-14 73 views
7

如果有幫助,我要的是類似於在此google tutorial交易android的結果片段

完成,但有一個片段到過渡之前創建的。如果我這樣做,轉換工作正常;但我不能使用這種方法

=====

旨在API 7+我只是想有一個片段,在整個屏幕上可見,並使用按鈕(按鈕繪製,用onTouch事件)然後交替到第二個片段,反之亦然。

但是,當我用第二個替換第一個片段時,或者我使用fragmentTransaction.show和fragmentTransaction.hide;在我看到空白屏幕之前,我可以切換兩次。我不想在後臺。

我創造的MainActivity的onCreate片段:

DiceTable diceTable = new DiceTable(); 
Logger logger = new Logger(); 
fragmentTransaction.add(diceTable, DICETABLE_TAG); 
fragmentTransaction.add(logger, LOGGER_TAG); 
fragmentTransaction.add(R.id.fragment_container, logger); 
fragmentTransaction.add(R.id.fragment_container, diceTable); 

然後在一個方法(從片段調用)我做的開關:

Logger logger = (Logger)fragmentManager.findFragmentByTag(LOGGER_TAG); 
    DiceTable diceTable = (DiceTable)fragmentManager.findFragmentByTag(DICETABLE_TAG); 

    if (diceTable.isVisible()) { 
     fragmentTransaction.replace(R.id.fragment_container, logger); 

     fragmentTransaction.commit(); 
     fragmentTransaction.hide(diceTable); 
     fragmentTransaction.show(logger); 
    } 
    else if (logger.isVisible()) { 
     fragmentTransaction.replace(R.id.fragment_container, diceTable); 

     fragmentTransaction.commit(); 
     fragmentTransaction.hide(logger); 
     fragmentTransaction.show(diceTable); 
    } 

這不是我應該怎麼做?替換片段

黑屏

回答

6

嘗試以這種方式初始化片段:

private void initFragments() { 
    mDiceTable = new DiceTable(); 
    mLogger = new Logger(); 
    isDiceTableVisible = true; 

    FragmentManager fm = getSupportFragmentManager(); 
    FragmentTransaction ft = fm.beginTransaction(); 
    ft.add(R.id.fragment_container, mDiceTable); 
    ft.add(R.id.fragment_container, mLogger); 
    ft.hide(mLogger); 
    ft.commit(); 
} 

然後以這種方式它們之間翻轉:

private void flipFragments() { 
     FragmentManager fm = getSupportFragmentManager(); 
     FragmentTransaction ft = fm.beginTransaction(); 
     if (isDiceTableVisible) { 
      ft.hide(mDiceTable); 
      ft.show(mLogger); 
     } else { 
      ft.hide(mLogger); 
      ft.show(mDiceTable); 
     } 
     ft.commit(); 
     isDiceTableVisible = !isDiceTableVisible; 
    } 
1

您正在結合該片段被示出變化的兩種不同的方法:

  • 調用replace()與不同片段
  • 調用hide()更換容器的內容物刪除一個片段,然後調用show()顯示另一個片段。

選擇一種方法並堅持下去。構建一個靈活的用戶界面指南只使用replace()方法,所以我會開始嘗試刪除所有對show()hide()的呼叫。

另請參閱Android Fragments: When to use hide/show or add/remove/replace?以便快速總結何時使用hide/show替代替換可能會有所幫助。