2016-09-24 30 views
3

我正在嘗試創建由多個其他片段組成的片段。 首先,我有一個覆蓋整個佈局的片段,您可以使用PagerAdapter向左或向右滑動其他片段。 這些碎片中的每一個都將由其他碎片組成。目前它由一個textView,一個按鈕和一個片段組成(將通過較小的調整重複該片段的重複)。片段只能在返回前一頁時正常工作

在每個fullscreen-fragment上,我通過將它附加到TextView來顯示我正在處於哪個頁面。這工作。

我想動態添加較小的Fragment。這不起作用。 它可以在加載的第一頁上工作,並且當你去回到前一頁(只有確切的前一個)時,它似乎仍在工作,即使它在第一次打開頁面時沒有顯示正方形。此行爲在此顯示: enter image description here

您可以看到文本顯示片段編號。但藍色方塊應該在每一個片段。這裏有什麼可能是錯的?

CreateView的()中的片段的方法,包括:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 

    View view = inflater.inflate(R.layout.fragment_level_selector, container, false); 

    Bundle bundle=getArguments(); 
    levelNumber=bundle.getInt("levelNumber"); 

    textView = (TextView) view.findViewById(R.id.text); 
    textView.append(" " + levelNumber.toString()); 

    String[] colors = {"#0000ff", "#00ff00", "#ff0000", "#ffff00"}; 

    FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction(); 
    ft.replace(R.id.include1, PictureFragment.newInstance(1, "#0000ff")); 
    ft.commit(); 

    return view; 
} 

片段佈局XML

<TextView android:id="@+id/text" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Hello, I am a TextView" /> 

    <FrameLayout 
     android:id="@+id/include1" 
     android:transitionName="pic1" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 
    </FrameLayout> 

    <Button android:id="@+id/button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:transitionName="pos1" 
     android:text="Hello, I am a Button" 
     android:onClick="sendMessage"/> 

編輯:這種行爲是僅當setOffscreenPageLimit(0)。如果我把它設置的更高,只有第一個打開的頁面有藍色方塊,所有其他人都沒有。對我來說,好像getResources()。getIdentifier()方法總是返回第一頁中的對​​象?這是真的嗎?

+1

愛GIF動畫與文字說明一起展現的概率到底是什麼。更多的問題應該是這樣的話和可視化。 –

+1

一個有用的小東西就是將代碼片段包裝在類和方法中,就像編寫代碼時一樣。 –

+1

爲什麼你有一個只迭代一次的for循環? –

回答

1

問題在於,ft.replace()用Code-Apprentice對原始問題的評論代替了它找到的第一個視圖。

更改

FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction(); 

FragmentTransaction ft = getChildFragmentManager().beginTransaction(); 

似乎已經解決了這個問題!

解決方案來源:ViewPager with multiple fragment instances of same class