2017-03-18 160 views
0

我已经看了其他答案,但没有人能帮助我。 我确保使用import android.support.v4.app.Fragment;,所以这不是问题。无法解析FragmentTransaction.add()方法。为什么我得到这个错误?

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> 

回答

3

马虎的错误。你应该叫v4.app.Fragment,而不是app.Fragment

打开myFragment.java

不要

import android.app.Fragment; 

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

改变这

import android.app.Fragment; 

import android.support.v4.app.Fragment; 

myFragment

此外,我会建议为你的片段正确的命名约定。

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