ViewPager的用法

代码如下所示:

public class MainActivity extends Activity {
    private ViewPager viewPager;
    private Listlist;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager= (ViewPager) findViewById(R.id.viewpager);
        list=new ArrayList();
        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 Listlist;
        public ViewPagerShiPei(Listlist) {
            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文件中



    

    

补充一下,后来再用viewpager,用上面的代码就报错了,需要用下面的代码,代码如下:

public class ShiYan extends AppCompatActivity {
    @BindView(R.id.viewpager)
    ViewPager viewPager;
    private List 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);
            }
        });
    }

}

你可能感兴趣的:(ViewPager的用法)