代码如下所示:
public class MainActivity extends Activity {
private ViewPager viewPager;
private List<View>list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager= (ViewPager) findViewById(R.id.viewpager);
list=new ArrayList<View>();
list.add(getLayoutInflater().inflate(R.layout.viewpager,null));
list.add(getLayoutInflater().inflate(R.layout.viewpager2,null));
viewPager.setAdapter(new ViewPagerShiPei(list));
}
class ViewPagerShiPei extends PagerAdapter{
private List<View>list;
public ViewPagerShiPei(List<View>list) {
this.list=list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(list.get(position));
return list.get(position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
container.removeView(list.get(position));
}
}
}
在activity_main.xml文件中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/viewpager">
</android.support.v4.view.ViewPager>
</LinearLayout>
补充一下,后来再用viewpager,用上面的代码就报错了,需要用下面的代码,代码如下:
public class ShiYan extends AppCompatActivity {
@BindView(R.id.viewpager)
ViewPager viewPager;
private List<View> list;
private String[] s = {"第一个", "第二个", "第三个"};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shiyan);
ButterKnife.bind(this);
list = new ArrayList<>();
list.add(View.inflate(ShiYan.this, R.layout.viewpager, null));
list.add(View.inflate(ShiYan.this, R.layout.viewpager, null));
list.add(View.inflate(ShiYan.this, R.layout.viewpager, null));
viewPager.setAdapter(new PagerAdapter() {
@Override
public int getCount() {
return list.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(list.get(position));
return list.get(position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
});
}
}