【问题标题】:Android Fragment for tablets and phone适用于平板电脑和手机的 Android Fragment
【发布时间】:2013-02-26 19:42:50
【问题描述】:

我想做这样的事情。图片比文字更容易:

当用户点击 Fragment B 上的按钮时,Fragment 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();

这部分效果很好。

我现在有两个问题:

  • 这两种方式如何在主Activity中改变内容?我的意思是,在主要活动中,片段应该调用第二种方式,但在正常活动中,我需要调用第一种。

  • 如果我单击片段 A 中的一个项目,然后单击片段 B 中的按钮,该按钮会将片段更改为 NextFragment。如果我点击另一个项目,我也会这样做。我可以回到第一个用户。点击新项目时有没有办法转储堆栈?

感谢您的帮助。

Ps:我使用的是原生片段库而不是支持 v4。

【问题讨论】:

    标签: android android-fragments fragment


    【解决方案1】:

    我很难理解您的 2 个问题的具体细节,因为它们含糊不清且没有提供足够的细节。

    但是,由于您希望在运行时更改您的 Fragments,您不应该&lt;fragment/&gt; 放入您的布局文件中。您当前的架构无法更改布局中的Fragments,这不是您想要的。

    注意:当您通过在布局 XML 文件中定义片段来将片段添加到活动布局时,您无法在运行时删除该片段。如果您计划在用户交互期间交换片段,则必须在 Activity 首次启动时将片段添加到 Activity。

    您应该在您的布局文件中为您的Fragments 使用FrameLayout 容器,并根据如果他们在那里。这将允许应用程序创建 1 个纵向的 Fragment 和 2 个横向的 Fragments(假设您有每个方向的布局)。这也将允许您随意更换Fragments,并将它们添加到后台堆栈。

    可以在here 找到这种 Google 推荐方法的示例。

    【讨论】:

    • 谢谢,我会用一些FrameLayout替换布局。
    • 问我问题的更好方法:如何确定片段是以“双模式”还是简单模式调用的?
    • 根据FrameLayout 容器,它会进入提供的布局。如果它有fragment_container_a,它添加FragmentA,如果它有fragment_container_b,它添加FragmentB。就像在 Google 示例中一样,if (findViewById(R.id.fragment_container_a) != null)。然后,您只需创建一个带有fragment_container_a 的纵向布局并将其放入layout 文件夹,然后创建一个带有fragment_container_afragment_container_b 的横向布局并将其放入layout-land 文件夹中。现在根据Activity 获得的布局,它添加了正确的Fragments。
    【解决方案2】:

    您可以从here 找到一个好的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多