无法解析FragmentTransaction.add()方法。为什么我收到此错误?

时间:2017-03-18 06:17:51

标签: android android-fragments fragmenttransaction

我已经查看了其他答案,但没有一个能帮助我。 我确保使用import android.support.v4.app.Fragment;这样就不会出现问题了。

MainActivity.java

     package com.example.nirvan.fragmentsexample2;


    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;

    public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myFragment myfragment=new myFragment();
        FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.fragmentContainer,myfragment);
        fragmentTransaction.commit();

    }
   }

错误

Error:(20, 28) error: no suitable method found for add(int,myFragment)
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; myFragment cannot be converted to Fragment)

为什么我会这样做?

activity_main.xml 中,我有FrameLayout

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff0000"
    android:id="@+id/fragmentContainer">

</FrameLayout>

myFragment.java

package com.example.nirvan.fragmentsexample2;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;    
import android.view.View;
import android.view.ViewGroup;
public class myFragment extends Fragment
{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle 
 savedInstanceState)
{
    return inflater.inflate(R.layout.fragment,container,false);
}

public myFragment(){}
}

fragment.xml之

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:paddingLeft="145dp"
    android:text="fragment One"/>

</RelativeLayout>

2 个答案:

答案 0 :(得分:5)

马虎错误。您应该拨打 v4.app.Fragment ,而不是 app.Fragment

打开 myFragment.java

<强>不

import android.app.Fragment;

<强>不要

import android.support.v4.app.Fragment;

答案 1 :(得分:4)

更改此

import android.app.Fragment;

import android.support.v4.app.Fragment;
myFragment

中的

我还建议你的片段有适当的命名约定。

相对布局中不需要android:orientation="vertical"