片段管理器事务错误的参数类型

Fragment manager transaction wrong argument type

我正在处理一个导航抽屉,其中包含两个不同的片段。不工作的是 fragmentManager.beginTransaction().replace(R.id.fragment, first).commit(); 中的“first”和“second”以及下面的 java 文件中的另一行。它引发的错误是:

Wrong 2nd argument type. Found: 'com.example.name_of_app.First', required: 'android.support.v4.app.Fragment' 

replace
(int,
android.support.v4.app.Fragment)
in FragmentTransaction cannot be applied
to
(int,
com.example.name_of_app.First)
 

MainActivity.java 文件中出现问题的部分:

public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            setTitle("First Fragment");
            First first = new First();
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.fragment, first).commit();
        } else if (id == R.id.nav_gallery) {
            setTitle("Second Fragment");
            Second second = new Second();
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.fragment, second).commit();

        } 

这是First.java片段

import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 */
public class First extends Fragment {


    public First() {
        // 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_first, container, false);
    }

}

和 fragment_first.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context="First">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="50dp"

        android:text="@string/hello_blank_fragment" />

</FrameLayout>

如果您查看错误,您会看到 android.support.v4.app.Fragment。但是,您的 class First 具有 import android.app.Fragment; 导入。

他们不匹配。将导入更改为 import android.support.v4.app.Fragment;