ranjith ranjith - 1 year ago 91
Android Question

can i use view pager with views (not with fragments)

I am using

for swiping b/w
, but can I use
to swipe b/w
simple xml layout?

This is my page
for the ViewPager which is used to swipe between Fragments:

import java.util.List;

import com.app.name.fragments.TipsFragment;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;

public class PageAdapter extends FragmentPagerAdapter {

List<Fragment> fragments;
public PageAdapter(FragmentManager fm,List<Fragment> frags) {
fragments = frags;


public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
return TipsFragment.newInstance(0, 0);

public int getCount() {
// TODO Auto-generated method stub
return 4;

public void destroyItem(ViewGroup container, int position, Object object) {
FragmentManager manager = ((Fragment) object).getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove((Fragment) object);

super.destroyItem(container, position, object);


And this is my tip fragment:

public class TipsFragment extends Fragment
public static TipsFragment newInstance(int image,int content)
TipsFragment fragment = new TipsFragment();
return fragment;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tip_layout, null);
return view;

How can I modify my code to work with Views instead of Fragment?

Answer Source

You need to override this two methods rather than getItem()

    public Object instantiateItem(ViewGroup collection, int position) {
        View v = layoutInflater.inflate(...);
        ((ViewPager) collection).addView(v,0);
        return v;

    public void destroyItem(ViewGroup collection, int position, Object view) {
        ((ViewPager) collection).removeView((TextView) view);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download