2016-03-01 21 views
0

您好我有以下情況的已經添加後膨脹視圖:如何分辨一個片段沒有查看

我加入一個碎片,無一UI做一些後臺工作

FragmentTransaction ft = getFragmentManager().beginTransaction(); 
ft.add(btFragment, "btFragmentAsBackgroundWorker"); 
ft.commit(); 

添加後,它不會顯示給用戶。所以它工作得很好。但有一點用戶可以訪問該片段來改變一些東西,所以我必須用UI來展示它。

爲了顯示它,我使用它像這樣

FragmentTransaction ft = getFragmentManager().beginTransaction(); 
ft.remove(menuFragment).show(btFragment); 
ft.commit(); 

但顯然沒有查看充氣。我怎樣才能做到這一點?

我想這一點,但我得到一個錯誤

ft.remove(menuFragment).add(R.id.fragmentMenu, btFragment); 

錯誤:

java.lang.IllegalStateException: Fragment already added: BTFragment{5c942bb #1 id=0x7f0c0072 btFragmentAsBackgroundWorker} 

回答

0

改變你的代碼如下....

無需視圖中添加片段

FragmentTransaction ft = getFragmentManager().beginTransaction(); 
ft.add(btFragment, "btFragmentAsBackgroundWorker"); 
ft.commit(); 

添加視圖

ft.replace(R.id.fragmentMenu,btFragment); 
    ft.commit(); 
+0

我不想刪除btFragment,因爲我有活動的線程在那裏工作。如果我刪除它們,它們都會被破壞。 –

+0

檢查編輯可能會幫助你 –

+0

我試過了,它基本上和remove()。add()一樣,並且它不起作用,因爲已經添加了片段 –

0

創建視圖是片段生命週期的一部分,不能真正推遲。我建議您至少在onCreateView()中創建一個空容器ViewGroup。然後,您可以稍後將視圖添加到容器。

或者,可以考慮創建一個可見性爲GONE的視圖,並在準備好顯示UI時將其設置爲VISIBLE

0

To add a fragment without a UI, add the fragment from the activity using add(Fragment, String) (supplying a unique string "tag" for the fragment, rather than a view ID). This adds the fragment, but, because it's not associated with a view in the activity layout, it does not receive a call to onCreateView(). So you don't need to implement that method.

Supplying a string tag for the fragment isn't strictly for non-UI fragments—you can also supply string tags to fragments that do have a UI—but if the fragment does not have a UI, then the string tag is the only way to identify it. If you want to get the fragment from the activity later, you need to use findFragmentByTag().