6

I have the following xml file:

  <android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

I have three fragments in the view pager. In one of the fragment I'm trying to launch a new fragment using this code :

FragmentTransaction trans = getFragmentManager()
                .beginTransaction();
        trans.replace(R.id.pager, new SubscriptionFragment());
        trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        trans.addToBackStack(null);

        trans.commit();

I'm able to successfully replace the existing fragment of the ViewPager, but it doesn't serve my purpose, what I desire to do is to not replace the existing fragment already present in the viewPager, but to remove the view pager itself from the view and launch a new Fragment so that the top tabs are no longer visible and ViewPager goes of the view. This works when I launch a new activity using intent. but isn't working for a fragment.

Edited :

public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, new MainFragment()).commit();
    }


}

MainFragment:

public class MainFragment extends Fragment {

    FragmentPagerAdapter adapterViewPager;
    ViewPager viewPager;
    String title[] = {"Services", "You", "History"};

    // TODO: Rename and change types and number of parameters
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        /* Inflate the layout for this fragment */
        View view = inflater.inflate(R.layout.fragment_view_pager, container, false);




        /*************************************/
        //CALLING HISTORY API

        //  loadSubscriptions();

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        ViewPagerAdapter mAdapter = new ViewPagerAdapter(getFragmentManager());

        ViewPager mPager = (ViewPager) getView().findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);
    }

    public static class ViewPagerAdapter extends FragmentPagerAdapter {
        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int num) {
            if (num == 0) {
                return new ServicesFragment();
            } else {
                return new HistoryFragment();
            }
        }

        @Override
        public int getCount() {
            return 2;
        }
    }
}

activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

</FrameLayout>

fragment_view_pager.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

In servicefragment : I'm openig new fragment using :

physiotherapyView.setOnClickListener(new View.OnClickListener() {





 @Override

        public void onClick(View view) {

            FragmentTransaction trans = getFragmentManager()
                    .beginTransaction();
            /*
             * IMPORTANT: We use the "root frame" defined in
             * "root_fragment.xml" as the reference to replace fragment
             */
            trans.replace(R.id.pager, new SubscriptionFragment());

            /*
             * IMPORTANT: The following lines allow us to add the fragment
             * to the stack and return to it later, by pressing back
             */
            trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            trans.addToBackStack(null);

            trans.commit();

        }

    });
2
  • is the ViewPager inside Fragment too? Jun 18, 2015 at 9:00
  • @ItzikSamara no its inside an Activity ! Jun 18, 2015 at 9:30

2 Answers 2

1

Below is the complete code to add or remove Fragments to or from a View pager. Since this is just a demonstration I have used just a textView and each fragment added will have a random colour.On clicking a button you can add as many fragments as you want.On clicking the Page you can just remove it from the View Pager.You can move from one Page to another in a View Pager by Swiping to the right or left.

MainActivity.java

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.Random;

public class MainActivity extends FragmentActivity {

    private MyPagerAdapter mpg;
    private ArrayList<MyFragment> fragmentlist = new ArrayList<>();
    public FragmentManager fmr    = getSupportFragmentManager();

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

        final ViewPager pager  = (ViewPager) findViewById(R.id.viewPager);
        mpg = new MyPagerAdapter(fmr,fragmentlist);
        pager.setAdapter(mpg);

        for (int q = 0; q < 5; q++) {
            int r = new Random().nextInt(100) + 155;
            int g = new Random().nextInt(100) + 155;
            int b = new Random().nextInt(100) + 155;
            fragmentlist.add(MyFragment.newInstance(q, "Page number: " + (q + 1), Color.rgb(r, g, b)));
            mpg.notifyDataSetChanged();
        }

        Button  B1 = (Button) findViewById(R.id.button);
        B1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int r = new Random().nextInt(100) + 155;
                int g = new Random().nextInt(100) + 155;
                int b = new Random().nextInt(100) + 155;
                int count = mpg.getCount();
                fragmentlist.add(MyFragment.newInstance(count, "Page number: " + (count+1), Color.rgb(r, g, b)));
                mpg.notifyDataSetChanged();

            }
        });
    }

    public void delete(int pos) {

        int i = 0;
        while (i <= fragmentlist.size()) {
            if (pos == fragmentlist.get(i).getPosition()) break;
            i++;

        }

        fragmentlist.remove(i);
        mpg.notifyDataSetChanged();
    }

    public class MyPagerAdapter extends FragmentStatePagerAdapter {

        private ArrayList<MyFragment> fragmentList;
        public MyPagerAdapter(FragmentManager fm, ArrayList<MyFragment> f) {
            super(fm);
            this.fragmentList = f;
        }

        @Override
        public Fragment getItem(int pos) {
            return fragmentlist.get(pos);
        }

        @Override
        public int getCount() {
            return fragmentlist.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }
}

MyFragment.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import java.util.List;

public class MyFragment extends Fragment {

    int pos;

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.f_1, container, false);
        pos = getArguments().getInt("num");
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.v("MainActivity", "Deleting at pos - " + pos);
                MainActivity activity = (MainActivity) getActivity();
                activity.delete(pos);
            }
        });

        TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
        FrameLayout fl = (FrameLayout) v.findViewById(R.id.frame_layout);
        tv.setText(getArguments().getString("msg"));
        fl.setBackgroundColor(getArguments().getInt("colour"));
        return v;
    }

    public int getPosition() {
        return pos;
    }

    public static MyFragment newInstance(int num,String text,int clr) {

        MyFragment f = new MyFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);
        b.putInt("colour", clr);
        b.putInt("num",num);
        f.setArguments(b);
        return f;
    }
}

And the xml.files,

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.shakthivels.assingment10.MainActivity"
    android:id="@+id/r_v"
    >

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/viewPager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ADD a fragment"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

f_1.xml

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

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/frame_layout">

        <TextView
            android:id="@+id/tvFragFirst"
            android:layout_width="203dp"
            android:layout_height="127dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:textSize="26sp"
            android:text="TextView"
            android:layout_gravity="center"
            android:textColor="#000000" />

    </FrameLayout>
</RelativeLayout>

Already Existing Fragment1 Newly added Fragment to the view Pager2

0

Do not Add, ViewPager Inside FrameLayout.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

</FrameLayout>

Add Fragment in this layout, which contains ViewPager and add FragmentTransaction in your mainActivity

    public class MainActivity extends FragmentActivity {


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, new MainFragment()).commit();

Here, MainFragment contains ViewPager, Now you can replace your viewPager from entire layout with FragmentTransaction

7
  • i already got you, please check whether the answer is suitable or not
    – Abhishek
    Jun 18, 2015 at 9:59
  • I didn't get what you are trying to say. You mean to say that I need to create a new class and extends FragmentActivity . And put the viewPager inside a Fragment instead of an activity? Jun 18, 2015 at 10:18
  • Your Activity will only have a framelayout and a separate fragment will contain the viewpager.
    – Abhishek
    Jun 18, 2015 at 10:37
  • I have edited my question. I have done the changes you have suggested but still facing the same issue Jun 18, 2015 at 11:49
  • trans.replace(R.id.pager, new SubscriptionFragment()); change it to trans.replace(R.id.frame_layout, new SubscriptionFragment());
    – Abhishek
    Jun 18, 2015 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.