在开发人员指南中,可以说Fragment
可以在运行时以编程方式添加到现有ViewGroup
。我的问题是:这个ViewGroup
如何链接到应用程序?
到目前为止,我已尝试在描述应用程序布局的xml文件中声明ViewGroup
。但是当我尝试使用Fragment
函数向其添加public abstract FragmentTransaction add (int containerViewId, Fragment fragment, String tag)
时,我的应用程序崩溃了(不是立即崩溃,而是在我的应用程序的onCreate
函数的末尾)。
我真正想要做的是在我的应用程序中管理多个视图(实现为Fragment
),并根据用户的选择在它们之间切换。我应该在我的方法中添加(或更改)什么?
提前感谢你花时间去帮助我。
答案 0 :(得分:5)
ViewGroup可以是简单的框架布局
<FrameLayout
android:id="@+id/fragmentForChange"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
然后用你的片段替换这个帧你需要做nex:
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);
答案 1 :(得分:1)
我不知道你的崩溃的原因是什么,因为你没有提供任何细节,只是给你一个提示(它对我有用,而且不像Fragment API那么明显,不能使用)。
请记住,FragmentTransaction中创建的Fragment不会立即添加,而是由其自行决定(稍后,可能在UI线程不忙时),因此Fragment的getView()调用可能会返回null一段时间,这可能是导致崩溃的原因。
我不清楚为什么Google会这样设计,因为API的其余部分是同步的 - 这更令人困惑 - 如果你创建Fragment作为XML布局的一部分(使用inflater),它会同步创建同样,getView总是返回值。
这可能是一种解决方法:如果您将ViewGroup创建为花药布局通胀过程的一部分,它可能对您有用。