错误:typesFragmentTransaction中的方法add(int,Fragment,String)不适用于参数(int,FragementTest,String)

我试图使用Fragements。 但在MainActivity.java文件中, transaction.add(R.id.my_layout, testfrag, ""); 没有正确启动。请在下面find我使用的代码。

 package com.example.testtabs; import android.os.Bundle; import android.app.Activity; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.app.TabActivity; import android.view.Menu; import android.widget.TabHost; import android.support.v4.app.Fragment; import com.example.testtabs.R; public class MainActivity extends TabActivity { TabHost tab; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragementTest testfrag=new FragementTest(); FragmentManager manager=getFragmentManager(); FragmentTransaction transaction=manager.beginTransaction(); transaction.add(R.id.my_layout, testfrag, "");//Error is here } } 

activity_main.xml:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:id="@+id/my_layout" > 

 Error: The method add(int, Fragment, String) in the type FragmentTransaction is not applicable for the arguments (int, FragementTest, String) 

Fragement.test

 package com.example.testtabs; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * A simple {@link android.support.v4.app.Fragment} subclass. * */ public class FragementTest extends Fragment { public FragementTest() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_fragement, container, false); } } 

更改:

 import android.app.FragmentManager; import android.app.FragmentTransaction; 

至:

 import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; 

要么 – –

更改:

 import android.support.v4.app.Fragment; 

 import android.app.Fragment; 

所有的片段应该是android.app.Fragment。如果你想使用android.support.v4.app.Fragment,你应该使用etSupportFragmentManager()来获取pipe理器。

它为我工作:

而不是使用getFragmentManager使用getSupportFragmentManager();