无法开始碎片交易

Can not begin Fragement Transaction

我试图将 Fragment 添加到 Activity,但是当我使用 beginTransaction 方法将 Fragment 添加到 Activity 编译器时 return 错误

cannot resolve method add

onCreate函数哪里出错return

   @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.contain, new PlaceholderFragment())
                .commit();
    }
}

片段

 public static  class PlaceholderFragment extends Fragment  {

    public PlaceholderFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.start, container, false);
        rootView.findViewById(R.id.start).setOnClickListener((View.OnClickListener) this);
        return rootView;
    }
}

main.xml

    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/contain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
     />

start.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<LinearLayout
    android:layout_gravity="center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical">
    <at.markushi.ui.CircleButton
        android:id="@+id/start"
        android:layout_width="163dp"
        android:layout_height="162dp"
        app:cb_pressedRingWidth="8dip"
        android:layout_gravity="center_horizontal|bottom"
        android:layout_alignParentBottom="true"
        android:layout_alignLeft="@+id/image"
        android:layout_alignStart="@+id/image"
        android:src="@drawable/start"
        android:layout_marginBottom="37dp"
        android:layout_alignRight="@+id/image"
        android:layout_alignEnd="@+id/image"
        android:layout_below="@+id/image" />
</LinearLayout>

消息Gradle构建

Error:(77, 21) error: no suitable method found for add(int,PlaceholderFragment) method FragmentTransaction.add(Fragment,String) is not applicable (argument mismatch; int cannot be converted to Fragment) method FragmentTransaction.add(int,Fragment) is not applicable (argument mismatch; PlaceholderFragment cannot be converted to Fragment)

将 extends Activity 更改为 FragmentActivity 以支持其中的片段

记得用

import android.support.v4.app.Fragment;

而不是

import android.app.Fragment;

这样您的片段来自支持库。否则,编译器无法解析方法 add 的参数类型,从而导致错误。