Sahil Tamhankar Sahil Tamhankar - 5 months ago 38
Android Question

Android Studio 2.1 Linking Fragment

//Main activity.java

package com.example.sahilnitish.easyyagriculture;

import android.app.Activity;

import android.app.FragmentManager;

import android.app.FragmentTransaction;

import android.support.v4.app.Fragment;

import android.os.Bundle;
import android.view.View;

import android.widget.Button;

public class MainActivity extends Activity
{

boolean status=false;

Button bn;

@Override

protected void onCreate(Bundle savedInstanceState)
{

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

bn=(Button)findViewById(R.id.bn);

bn.setOnClickListener(new View.OnClickListener()
{
@Override

public void onClick(View v)



{
FragmentManager fragmentManager = getFragmentManager();

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if(!status)
{
Fragmentone f1 =new Fragmentone();

fragmentTransaction.add(R.id.fragment_container,f1);
fragmentTransaction.commit();
bn.setText("Load Second fragment");
status=true;
}
else
{
FragmentTwo f2 = new FragmentTwo();
fragmentTransaction.add(R.id.fragment_container,f2);

fragmentTransaction.commit();
bn.setText("Load first fragment");
status=false;
}

}
});
}
}


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

fragmentone.java
package com.example.sahilnitish.easyyagriculture;

import android.os.Bundle;

import android.support.v4.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

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

public Fragmentone()

// 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_one_layout, container, false);
}


}

Answer

This is happening because you're using wrong FragmentManager.

So, first change your import statement from :

import android.app.FragmentManager;

to :

import android.support.v4.app.FragmentManager;

and also you should use getSupportFragmentManager().

so change :

FragmentManager fragmentManager = getFragmentManager();

to :

FragmentManager fragmentManager = getSupportFragmentManager();