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<View> 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<View>();
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<View> viewLists;
public MyPagerAdapter(ArrayList<View> 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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="@+id/ViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
item1(页面1,其他基本类似)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/colorAccent"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
item2(页面2)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/colorAccent"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
item3(页面3)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/colorAccent"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>