ViewPager的简单使用

MainActivity

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

private ViewPager vp;
private ArrayList aList;
private MyPagerAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    vp = (ViewPager) findViewById(R.id.ViewPager);

    aList = new ArrayList();
    LayoutInflater li = getLayoutInflater();
    aList.add(li.inflate(R.layout.item1,null,false));
    aList.add(li.inflate(R.layout.item2,null,false));
    aList.add(li.inflate(R.layout.item3,null,false));
    mAdapter = new MyPagerAdapter(aList);
    vp.setAdapter(mAdapter);
    }
}

MyPagerAdapter

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;

public class MyPagerAdapter extends PagerAdapter {
    private ArrayList viewLists;

public MyPagerAdapter(ArrayList viewLists) {
    super();
    this.viewLists = viewLists;
}

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

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == object;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    container.addView(viewLists.get(position));
    return viewLists.get(position);
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView(viewLists.get(position));
    }
}

activity_main






item1(页面1,其他基本类似)





item2(页面2)





item3(页面3)




你可能感兴趣的:(ViewPager的简单使用)