2013-02-26 72 views
1

我想做類似的事情。一個畫面是比文字更容易: enter image description hereAndroid平板電腦和手機的片段

當上的片段B一個用戶點擊按鈕時,B片段改變,但不是A. 我做了兩個不同的佈局(肖像和一個土地)。第一個具有像

<?xml version="1.0" encoding="utf-8"?> 
<fragment 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:name="com.my.app.ContactsFragment" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/contacts_fragment" /> 

佈局我在我的片段佈局一個簡單的活動通話按鈕:

Intent intent = new Intent(getActivity(), NextActivity.class); 
startActivity(intent); 

而且土地一個是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

<fragment 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:name="com.my.app.ContactsFragment" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/contacts_fragment" /> 

<fragment 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:name="com.my.app.HomeFragment" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/fragment_container" /> 

</LinearLayout> 

我使用以下代碼更改內部片段:

FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction(); 
NextFragment nextFrag = new NextFragment(); 
ft.replace(R.id.fragment_container, nextFrag); 
ft.addToBackStack(null); 
ft.commit(); 

這部分工作正常。

我有兩個問題,現在:

  • 如何將這兩種方法來改變的主要活動內容?我的意思是,在主要活動中,片段應該是第二種方式,但在正常活動中,我需要調用第一種方式。

  • 如果我點擊片段A中的一個項目,然後點擊片段B中將片段更改爲NextFragment的按鈕。如果我點擊另一個項目,我也這樣做。我可以回到第一個用戶。點擊新項目時是否有辦法轉儲堆棧?

感謝您的幫助。

Ps:我正在使用本機碎片庫而不是支持v4。

回答

2

我很努力地理解你的2個問題的細節,因爲它們含糊不清,並且沒有給出足夠的細節。

但是,因爲你希望你的Fragment s到在運行時改變了,你不應在你的佈局文件放<fragment/>。您當前的體系結構無法更改佈局中的Fragment,這不是您想要的。

注意:通過在佈局XML文件中定義片段將片段添加到活動佈局時,無法在運行時刪除片段。如果您計劃在用戶交互過程中交換片段,則必須在活動首次啓動時將片段添加到活動中。

您應該使用FrameLayout容器爲您Fragment在你的佈局文件,並有Activity取決於它們是否有添加Fragment s到那些FrameLayout容器。這將允許應用在橫向創建1 Fragment縱向和2 Fragment s(假設您有針對每個方向的佈局)。這也將允許您可以根據自己的需要更換Fragment,並將它們添加到後端堆棧中。

而這個例子谷歌推薦的方法可以找到here

+0

謝謝,我將用一些FrameLayout替換佈局。 – Manitoba 2013-02-26 20:06:58

+0

一個更好的方式來問我的問題:如何確定片段是在「雙模式」還是簡單模式中調用? – Manitoba 2013-02-26 20:10:58

+0

根據「FrameLayout」容器,它獲取它提供的佈局。如果它具有'fragment_container_a',則它向其添加'FragmentA',如果它獲得'fragment_container_b',則它將'FragmentB'添加到它。就像在Google的例子中一樣,'if(findViewById(R.id.fragment_container_a)!= null)'。然後,您只需創建一個帶有'fragment_container_a'的肖像佈局,並將其放置在'layout'文件夾中,並使用'fragment_container_a'和'fragment_container_b'將橫向佈局放入'layout-land'文件夾中。現在取決於'Activity'的佈局,它增加了正確的'Fragment's。 – 2013-02-26 20:28:53

1

您可以從here找到一個很好的解決方案。