无法开始Fragement Transaction

时间:2015-09-14 02:00:56

标签: android android-fragments fragmenttransaction

我尝试将Fragment添加到Activity,但是当我beginTransaction方法将Fragment添加到Activity编译器时返回错误

  

无法解析方法添加

onCreate函数,其中错误返回

   @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 build

  

错误:(77,21)错误:找不到合适的add方法(int,PlaceholderFragment)   方法FragmentTransaction.add(Fragment,String)不适用   (参数不匹配; int无法转换为Fragment)   方法FragmentTransaction.add(int,Fragment)不适用   (参数不匹配; PlaceholderFragment无法转换为Fragment)

2 个答案:

答案 0 :(得分:1)

请记住使用

import android.support.v4.app.Fragment;

而不是

import android.app.Fragment;

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

答案 1 :(得分:0)

将您的扩展活动更改为FragmentActivity以支持其中的片段