AndroidStudio在布局中添加Viewpager

AndroidStudio在布局中添加Viewpager_第1张图片

要在安卓中做一个如图添加能够滑动的布局 viewpager。做法。

1、在布局中添加viewpager控件

    

2、编写viewpager的布局。

 




    

        

            

3、在代码中设置

two跟上边的一样

view1 = LayoutInflater.from(getActivity()).inflate(R.layout.home_viewpager_one, null);
view2 = LayoutInflater.from(getActivity()).inflate(R.layout.home_viewpager_two, null);

 

       mViewPager = (ViewPager) view.findViewById(R.id.home_viewpager);
        list.add(view1);
        list.add(view2);

 

设置适配器 

  private class GuideAdapter extends 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);
        }
    }

设置滑动展示下边横条变化

只需要两个图片就行

    private void setPoint(boolean isSelect1, boolean isSelect2) {
        if (isSelect1) {
            imageView1.setBackgroundResource(R.mipmap.home_viewpager_bottom_on);
            imageView2.setBackgroundResource(R.mipmap.home_viewpager_bottom_off);
        }
        if (isSelect2) {
            imageView1.setBackgroundResource(R.mipmap.home_viewpager_bottom_off);
            imageView2.setBackgroundResource(R.mipmap.home_viewpager_bottom_on);
        }
    }

监听滑动。设置适配器

    mViewPager.setAdapter(new GuideAdapter());
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        setPoint(true, false);
                        break;
                    case 1:
                        setPoint(false, true);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

这样就行了。

你可能感兴趣的:(AndroidStudio)