片段添加或replace不工作

我正在使用这个参考的代码。

当我把代码放在我的程序中时,会出现如下图所示的错误。 在这里输入图像描述

任何错误的原因? The method replace(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, ExampleFragments)

来自我主要活动的代码:

 public void red(View view) { android.app.FragmentManager fragmentManager = getFragmentManager(); android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); ExampleFragments fragment = new ExampleFragments(); fragmentTransaction.replace(R.id.frag, fragment); fragmentTransaction.commit(); } 

ExampleFragments.java

 package com.example.learn.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ExampleFragments extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.blue_pill_frag, container, false); } } 

这里:

 package com.example.learn.fragments; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; 

这里的问题是,你正在混合android.support.v4.app.Fragmentandroid.app.Fragment 。 您需要将所有用途转换为使用支持库,这也意味着调用getSupportFragmentManager()

像这样的东西,例如:

  android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager(); android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); ExampleFragments fragment = new ExampleFragments(); fragmentTransaction.replace(R.id.frag, fragment); fragmentTransaction.commit(); 

支持库Fragment和正常的Fragment是不可互换的。 他们达到相同的目的,但不能用代码相互replace。

虽然这个问题可能已经被回答了,但是应该注意到,重叠片段的解决scheme是用一个新的“片段”实例来获得片段ID(实际上,在xml中声明的FrameLayout id将导致头痛):

 FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); Fragment fragment = new ExampleFragments(); fragmentTransaction.replace(R.id.frag, fragment); fragmentTransaction.commit(); 

我无法告诉你,我花了多less小时后,通过邮寄没有解决scheme。 我在上面的评论中读到了你的其他post,我也会在那里回答,以防有人发现。

对于那些正在获得ClassCastException ,也可以试试这个。 您可以添加所有正确的库,使用FragmentActivity而不是Fragment ,并在代码中使用getActivity()。getSupportFragmentManager来停止ListFragment中的错误,并且仍会遇到Fragments问题。 Google文档不会告诉你所有的东西,而且Eclipse代码的完成并不总是可以节省你的时间……有时你只需要自己修复这个bug!

无论我尝试了什么(包括这里写的),直到我看到这个答案,我才解决了这个问题

https://stackoverflow.com/a/5907704/728312

这是为我工作的

android.app.FragmentManager fragmentManager = getActivity().getFragmentManager();