How to replace a fragment with another fragment using the listener in the first fragment


I am using two fragments in my activity.Initially I will add one fragment to the activity.Then using listener in first fragment I want replace it with second fragment. I tried as per my understanding ,but it is not replacing. It is showing both fragments overlapped.

Here is my code:

// MainActivity

public class MainActivity extends Activity {
    Fragment Fragment_one;
    Button one;

    protected void onCreate(Bundle savedInstanceState) {
        //one=(Button) findViewById(;
        //one.setOnClickListener(new View.OnClickListener() {

            //public void onClick(View arg0) {
                // TODO Auto-generated method stub
                FragmentManager man=getFragmentManager();
                FragmentTransaction tran=man.beginTransaction();
                Fragment_one=new Fragment1();
                tran.add(, Fragment_one);//tran.



//fragment code

public class Fragment1 extends Fragment{
    Button add;
    Fragment2 fragment_two;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        //return super.onCreateView(inflater, container, savedInstanceState);

        View view=inflater.inflate(R.layout.fragment_1, container,false);
        add=(Button) view.findViewById(;
        fragment_two =new Fragment2();
        add.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                FragmentTransaction t=getActivity().getFragmentManager().beginTransaction();
                t.remove( new Fragment1());

                t.replace(, fragment_two);t.addToBackStack(null);


        return view;

Couple of things I see in your code.

t.remove(new Fragment1());

This line of code won't do anything because you're trying to remove a new instance of Fragment1, not the instance you originally added.

t.replace(, fragment_two)

This the first parameter should be the id of the container "" not


This code may or may not be needed based on whether you want to allow the user to press the 'back' button to go back to fragment_one after they've arrived at fragment2.