Android常用控件之ViewPager

目录:android.support.v4.view.ViewPager

xml布局




    

代码使用:

public class MainActivity extends AppCompatActivity {
    private ViewPager vp_viewPager;
    private List list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        vp_viewPager = (ViewPager) findViewById(R.id.vp_viewPager);

        //子item是Fragment使用该适配器(推荐使用)
        vp_viewPager.setAdapter(new FmVpAdapter(getSupportFragmentManager()));

        //子item是view使用该适配器
//        list = new ArrayList<>();
//        for (int i = 0; i < 5; i++) {
//            TextView tv = new TextView(this);
//            tv.setText("我是界面"+i);
//            list.add(tv);
//        }
//        vp_viewPager.setAdapter(new VpAdapter(list));
        
    }

    //子item是Fragment使用该适配器
    private class FmVpAdapter extends FragmentPagerAdapter {
        public FmVpAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return new VpFragment();//每个碎片都会被标识,使用过的碎片会被复用
        }

        @Override
        public int getCount() {
            return 3;//更换自己数据源数量
        }
    }


    //子item是view使用该适配器
    private class VpAdapter extends PagerAdapter{
        List list;

        public VpAdapter(List list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0==arg1;
        }
        @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) {
            //.destroyItem(container, position, object);
            container.removeView(list.get(position));
        }
    }

}

碎片:

xml布局:fragment_vp_page.xml




    

碎片

public class VpFragment extends Fragment {
    private View view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_vp_page, null);
        init();
        return view;
    }

    private void init() {
        TextView tv_page = (TextView) view.findViewById(R.id.tv_page);

    }
}

注意:

1、Fragment导入的都是V4包的类

你可能感兴趣的:(Android常用控件之ViewPager)