2013-05-26 80 views
1

我有必要用兩個其他片段(B和C,在「常用」列表+查看器配置中)替換一個活動的一個起始片段(我將其稱爲A)。目前我有兩個框架佈局中充當B和C的佔位符相對佈局:兩個片段代替一個

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <RadioGroup 
     android:id="@+id/radiogroup_navigation" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" > 
     <!-- Some radiobuttons (not displayed for the sake of brevity) --> 
    </RadioGroup> 

<FrameLayout 
    android:id="@+id/frame_list" 
    android:layout_width="100dp" 
    android:layout_height="fill_parent" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentBottom="true" 
    android:layout_below="@id/radiogroup_navigation"> 
</FrameLayout> 

<FrameLayout 
    android:id="@+id/frame_view" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_alignParentRight="true" 
    android:layout_alignParentBottom="true" 
    android:layout_below="@id/radiogroup_navigation" 
    android:layout_toRightOf="@id/frame_list"> 
</FrameLayout> 

當我需要顯示,我只是隱藏frame_list和A添加到frame_view ,並且當我需要再次顯示B和CI時,請設置frame_list可見並在同一個分段事務中將這兩個片段添加到每個幀。

FragmentTransaction t = getSupportFragmentManager().beginTransaction(); 
t.remove(fragmentA); 
t.add(R.id.frame_list, fragmentB); 
t.add(R.id.frame_view, fragmentC); 
t.addToBackStack(null); 
t.commit(); 

這樣,當我按下後退按鈕時,C和B走開,我回片段,但現在frame_list是可見的(空)。

我想解決兩個可能的途徑問題:

  • 首要onBackPressed如果需要隱藏左幀;
  • 將B和C嵌套在另一個片段中;

但我也覺得我可能在錯誤的方式看問題,也許有一個更清潔的設計解決方案。你有什麼建議嗎?

回答

0

如果我理解正確的話,這裏是一個解決方案:

  1. 創建兩個活動ActivityA和ActivityBC
  2. 創建一個RadioGroup中
  3. 嵌入FragmentRadio到兩個ActivityA和ActivityBC
  4. 另一個片段有片段根據選擇開始新活動,同時完成當前活動
0

製作領域是這樣的:

private static final String FRAGMENT_B_TAG = "fragmentB"; 

當您添加的片段,使用靜態String就像標籤:

t.add(R.id.frame_list, fragmentB, FRAGMENT_B_TAG); 
t.add(R.id.frame_view, fragmentC, FRAGMENT_C_TAG); 

在你的活動上,建立一個監聽器,這將被觸發後,每次您致電addToBackStack(String)。它將找出哪個片段當前可見,並隱藏/顯示所需的容器。

getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() { 
    @Override 
    public void onBackStackChanged() { 
     FragmentA fa = getSupportFragmentManager().findFragmentByTag(FRAGMENT_A_TAG); 
     FragmentB fb = getSupportFragmentManager().findFragmentByTag(FRAGMENT_B_TAG); 
     if (fa != null && fa.isVisible()) { 
      // Fragment A is visible, so hide the second container which is now empty 
     } 
     if (fb != null && fb.isVisible()) { 
      // Fragment B is visible, so show the second container 
     } 
    } 
}); 

注意檢查Fragment C是否可見或不可見,因爲當Fragment B可見是不需要的,Fragment C始終可見了。

這是一個未經測試的代碼,但我認爲它應該工作。另外,如果您需要任何解釋,請不要猶豫,問。

希望它有幫助。

相關問題