【问题标题】:Can you build layouts inside of fragements in Honeycomb?你可以在 Honeycomb 的片段中构建布局吗?
【发布时间】:2011-06-21 01:20:15
【问题描述】:

我对 Android 有点陌生,对 Fragments 也很陌生。我正在尝试将应用程序从活动移植到 Honeycomb 的片段(嗯,活动 + 片段)。在我们进入平板电脑屏幕之前,我们希望我们的应用程序能够与 1.6+ 设备的片段兼容性库一起工作。我已阅读 Google 的文档和示例,没有明确说明我可以或不能执行以下操作,但它对我不起作用。

移植的第一个屏幕是启动器屏幕,它有一个名为 fragment_splash.xml 的布局文件

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/splash_background">
    <fragment class="...StartupFragmentLayout$StartupFragment"
        android:id="@+id/fragStartup" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/debugText"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:text="DEBUG ON"
            android:gravity="center"
            android:textSize="35sp"
            android:textColor="@color/blue_text"
            android:textStyle="bold"
            android:shadowColor="#FFFFFF"
            android:shadowRadius="2"/>
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0.4"
            android:gravity="bottom">
           ...
    </fragment>
</LinearLayout>

但是,这不起作用。我收到一条错误消息,指出 StartupFragmentLayout$StartupFragment 没有创建视图。我开始怀疑我不能在&lt;fragment&gt; 中嵌套任何东西,因为我没有在任何文档或示例中看到它。这是正确的,还是我的问题是别的?

【问题讨论】:

  • 既然您提到您正在使用 Fragment Compatibility Library,首先要检查的是您尝试用于启动屏幕的 Activity 是从 FragmentActivity 扩展而来的。如果是这种情况,并且您仍然收到错误,您能否发布确切的错误消息和/或堆栈跟踪?
  • 是的,我正在使用片段兼容性库。错误说“StartupFragmentLayout$StartupFragment 没有创建视图”,它发生在 setContentView(R.layout.fragment_splash);在 OnCreate 中
  • 在这种情况下,我会在下面查看 PJL 的回复 - 它似乎更符合 Fragments 的预期工作方式。

标签: android android-3.0-honeycomb android-fragments


【解决方案1】:

从文档中不清楚您是否可以在 &lt;fragment&gt; 中拥有子视图。鉴于没有片段样本这样做,那么我怀疑这不是它们的使用方式。您可以尝试将 &lt;fragment&gt; 更改为 &lt;FrameLayout&gt; 并在运行时将片段添加到其中,如果您真的愿意,看看是否可行。

但是,我认为您最好的解决方案是将您的子视图放入一个单独的布局文件中,然后在 onCreateView 中通过say 填充到片段的容器中:

final View iv = inflater.inflate(R.layout.favourites, container, false);

我不认为你会因为这样做而失去任何东西。

【讨论】:

  • 我想你不小心说了一句话。 “如果你真的想的话,你可以尝试在运行时更改为 a 并将片段添加到其中,看看是否可行。”这句话是什么意思。
  • @CACuzcatlan 它应该说 ."..将 更改为 " 我可以在我的屏幕上看到。
  • 我现在看到了,不知道是你编辑的还是我的浏览器昨天出了问题
【解决方案2】:

为了解决这个问题,片段在布局中不能有子级。 PJL 正在建议正确的方法。片段内的布局应在单独的 XML 文件中指定。然后,您可以通过从 Fragment 的 onCreateView 方法返回此布局来将该布局注入到视图树中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 2014-12-18
    • 2012-02-15
    相关资源
    最近更新 更多