0

我正在尝试使用以下代码打开Fragment另一个 Fragment 内的 a,但它给了我一个空指针异常,没有任何原因。

Fragment newFragment = new SecondFragment(); 
// consider using Java coding conventions (upper char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.menuitem_detail_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit(); 

这段代码在Fragment ( )内部方法的基本onItemClickListener内部onCreateViewandroid.support.v4.app.Fragment

关于我可能做错了什么的任何想法?

4

3 回答 3

2

在 getFragmentManager 上,您应该使用getActivity().getSupportFragmentManager()orgetChildFragmentManager()代替 getFragmentManager。如果 NPE 在 transaction.replace() 中被抛出,你应该确保你正在替换一个合适的布局,例如

RelativeLayout rl = (RelativeLayout) getActivity().findViewById(R.id.menuitem_detail_container);
transaction.replace(rl.getId(), newFragment);

以上只是一个例子,因为我不知道你的代码,但你可能会得到这个想法。在此示例中,我假设您使用的容器布局在活动 XML 中具有相同的名称。

只要确保您不要尝试替换返回 null 的内容。如果您正在使用 onCreate 中的容器,请尝试记录它以查明它是否为空。

如果这对您没有帮助,请发布您的 Logcat 输出。

于 2013-12-09T22:35:39.913 回答
0

当您使用嵌套片段时,您需要获取内部片段的getChildFragmentManager()

还要确保从 FragmentManager 和 ChildFragmentManager 的支持库中导入。

于 2013-12-09T22:23:12.183 回答
0

寻找我的 transaction.replace :

transaction.replace(R.id.provas_view, new ListaProvasFragment(), ListaProvasFragment.class.getCanonicalName());

于 2013-12-09T22:32:48.763 回答