2013-02-26 91 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找到一个很好的解决方案。