【问题标题】:Adding a Fragment to a ViewGroup将片段添加到视图组
【发布时间】:2011-08-21 09:32:42
【问题描述】:

在开发人员指南中,据说可以在运行时以编程方式将Fragment 添加到现有ViewGroup。我的问题是:这个ViewGroup 是如何链接到应用程序的?

到目前为止,我已经尝试在描述我的应用程序布局的 xml 文件中声明 ViewGroup。但是当我尝试使用public abstract FragmentTransaction add (int containerViewId, Fragment fragment, String tag) 函数向其添加Fragment 时,我的应用程序崩溃(不是立即崩溃,而是在我的应用程序的onCreate 函数结束时)。

我真正想做的是在我的应用程序中管理几个视图(实现为Fragment)并根据用户的选择在它们之间切换。我应该在我的方法中添加(或更改)什么?

提前感谢您花时间帮助我。

【问题讨论】:

  • 在 Eclipse 中使用 adb logcat、DDMS 或 DDMS 透视图检查 LogCat 并查看与您的崩溃相关的堆栈跟踪。

标签: java android fragment


【解决方案1】:

ViewGroup 可以是简单的框架布局

<FrameLayout
android:id="@+id/fragmentForChange"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>

然后用你需要做的片段替换这个框架:

Bundle args = new Bundle();        
// add needed args

//create fragment and set arguments    
Fragment fragment= MyFragment();
fragment.setArguments(args)

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// getSupportFragmentManager - uses for compatible library instead of getFragmentManager

//replace frame with our fragment
ft.replace(R.id.fragmentForChange,fragment);
//set type of animation
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

//finish transaction
ft.commit();

您可以使用命令隐藏或显示事务中的片段:

ft.hide(fragment);        
ft.show(fragment);        

【讨论】:

  • 添加不是替换。
【解决方案2】:

我不知道您崩溃的原因可能是什么,因为您没有提供任何详细信息,只是给您发送了一个提示(它对我有用,而且它并不明显,因为 Fragment API 使用起来不太直观)。

请记住,在 FragmentTransaction 中创建的 Fragment 不会立即添加,而是自行决定添加(稍后,可能在 UI 线程不忙时),因此 Fragment 的 getView() 调用可能会在一段时间内返回 null,这可能是导致崩溃的原因。

我不清楚为什么 Google 以这种方式设计它,因为 API 的其余部分是同步的,而且 - 这更令人困惑 - 如果您将 Fragment 创建为 XML 布局的一部分(使用 inflater),它是同步创建的以及 getView 总是返回值。

这是可能的解决方法:如果您创建 ViewGroup 作为另一个布局膨胀过程的一部分,它可能对您有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    相关资源
    最近更新 更多