欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

viewpager图片轮播

程序员文章站 2022-06-09 15:55:18
...

转载:https://www.cnblogs.com/luhuan/p/8047098.html
与启动页不同

  • 适配器需要改动返回值,取最大(无限)
  • 适配器和activity取位置要除以图片size取余数最为位置(无限)
  • 使用另一种方法添加小圆点(代码中添加),而不是xml静态设置
  • 设置了一个handle作为滑动(自动)
    修改完代码如下`

我是在fragement中创造的,可能和activity中有点不同

public class HomeFragment extends Fragment implements View.OnClickListener {

    //图片轮播
    LinearLayout linearLayoutDots;
    private ViewPager mViewPager;
    private ImageView iv;
    private TextView mTvPagerTitle;
    private List<ImageView> mImageList;//轮播的图片集合
    private String[] mImageTitles;//标题集合
    private int previousPosition = 0;//前一个被选中的position
    private List<View> mDots;//小点
    private boolean isStop = false;//线程是否停止
    // 在values文件假下创建了pager_image_ids.xml文件,并定义了4张轮播图对应的id,用于点击事件
    private int[] imgae_ids = new int[]{R.id.carousel1,R.id.carousel2,R.id.carousel3,R.id.carousel4};
    private  View view;

    public HomeFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false)
        mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
        mTvPagerTitle = (TextView) view.findViewById(R.id.tv_pager_title);
        linearLayoutDots = (LinearLayout) view.findViewById(R.id.lineLayout_dot);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initAction();
        initData();
        initViewPager();
        //autoPlayView();//开启线程,自动播放
        handler.sendEmptyMessageDelayed(0,2000);
    }



    /**
     * 控件初始化
     */
    protected void initView() {

    }

    /**
     * 事件监听
     */
    protected void initAction() {
    }

    /**
     * 数据处理
     */
    protected void initData() {

        //初始化标题列表和图片
        mImageTitles = new String[]{"这是一个好看的标题1","这是一个优美的标题2","这是一个快乐的标题3","这是一个开心的标题4"};
        int[] imageRess = new int[]{R.drawable.carousel1,R.drawable.carousel2,R.drawable.carousel3,R.drawable.carousel4};
        //添加图片到图片列表里
        mImageList = new ArrayList<>();
        for (int i = 0; i < imageRess.length; i++) {
            iv = new ImageView(getActivity());
            iv.setBackgroundResource(imageRess[i]);//设置图片
            iv.setId(imgae_ids[i]);//顺便给图片设置id
            iv.setOnClickListener(this);//设置图片点击事件
            mImageList.add(iv);
        }
        //添加轮播点
        mDots = addDots(linearLayoutDots,fromResToDrawable(getActivity(),R.drawable.selector_dots),mImageList.size());//其中fromResToDrawable()方法是我自定义的,目的是将资源文件转成Drawable
    }

    /**
     *  给PagerViw设置适配器,并实现自动轮播功能
     */
    private void initViewPager() {
        CircleViewPagerAdapter viewPagerAdapter = new CircleViewPagerAdapter(mImageList, mViewPager);
        mViewPager.setAdapter(viewPagerAdapter);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //伪无限循环,滑到最后一张图片又从新进入第一张图片
                int newPosition = position % mImageList.size();
                // 把当前选中的点给切换了, 还有描述信息也切换
                mTvPagerTitle.setText(mImageTitles[newPosition]);//图片下面设置显示文本
                //设置轮播点
                LinearLayout.LayoutParams newDotParams = (LinearLayout.LayoutParams) mDots.get(newPosition).getLayoutParams();
                newDotParams.width = 24;
                newDotParams.height = 24;
               mDots.get(newPosition).setLayoutParams(newDotParams);
               mDots.get(newPosition).setBackground(fromResToDrawable(getActivity(),R.drawable.dot_true));
                LinearLayout.LayoutParams oldDotParams = (LinearLayout.LayoutParams) mDots.get(previousPosition).getLayoutParams();
                oldDotParams.width = 16;
                oldDotParams.height = 16;
               mDots.get(previousPosition).setLayoutParams(oldDotParams);
                mDots.get(previousPosition).setBackground(fromResToDrawable(getActivity(),R.drawable.dot_false));
                // 把当前的索引赋值给前一个索引变量, 方便下一次再切换.
                previousPosition = newPosition;
            }
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        setFirstLocation();
    }

    /**
     * 设置刚打开app时显示的图片和文字
     */
    private void setFirstLocation() {
        mTvPagerTitle.setText(mImageTitles[previousPosition]);
        // 把ViewPager设置为默认选中Integer.MAX_VALUE / t2,从十几亿次开始轮播图片,达到无限循环目的;
        int m = (Integer.MAX_VALUE / 2) % mImageList.size();
        int currentPosition = Integer.MAX_VALUE / 2 - m;
        mViewPager.setCurrentItem(currentPosition);

       LinearLayout.LayoutParams newDotParams = (LinearLayout.LayoutParams) mDots.get(0).getLayoutParams();
        newDotParams.width = 24;
        newDotParams.height = 24;
        mDots.get(0).setLayoutParams(newDotParams);
        mDots.get(0).setBackground(fromResToDrawable(getActivity(),R.drawable.dot_true));
    }

    /**
     * 设置自动播放,每隔PAGER_TIOME秒换一张图片
     */
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            int item = mViewPager.getCurrentItem() +1;
            mViewPager.setCurrentItem(item);
            handler.sendEmptyMessageDelayed(0,2000);
        }
    };

    /**
     * 资源图片转Drawable
     * @param context
     * @param resId
     * @return
     */
    public Drawable fromResToDrawable(Context context, int resId) {
        return context.getResources().getDrawable(resId);
    }

    /**
     * 动态添加一个点
     * @param linearLayout 添加到LinearLayout布局
     * @param backgount 设置
     * @return
     */
    public int addDot(final LinearLayout linearLayout, Drawable backgount) {
        final View dot = new View(getActivity());
        LinearLayout.LayoutParams dotParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        dotParams.width = 16;
        dotParams.height = 16;
        dotParams.setMargins(8,0,8,0);
        dot.setLayoutParams(dotParams);
        dot.setBackground(fromResToDrawable(getActivity(),R.drawable.dot_false));
        //dot.setClickable(false);
        dot.setId(View.generateViewId());
        linearLayout.addView(dot);
        return dot.getId();
    }

    /**
     * 添加多个轮播小点到横向线性布局
     * @param linearLayout
     * @param backgount
     * @param number
     * @return
     */
    public List<View> addDots(final LinearLayout linearLayout, Drawable backgount, int number){
        List<View> dots = new ArrayList<>();
        for (int i = 0; i < number; i++) {
            int dotId = addDot(linearLayout,backgount);
            dots.add(view.findViewById(dotId));
        }
        return dots;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.carousel1:
                Toast.makeText(getActivity(), "图片1被点击", Toast.LENGTH_SHORT).show();
                break;
            case R.id.carousel2:
                Toast.makeText(getActivity(), "图片2被点击", Toast.LENGTH_SHORT).show();
                break;
            case R.id.carousel3:
                Toast.makeText(getActivity(), "图片3被点击", Toast.LENGTH_SHORT).show();
                break;
            case R.id.carousel4:
                Toast.makeText(getActivity(), "图片4被点击", Toast.LENGTH_SHORT).show();
                break;
        }
    }


}

xml文件

<FrameLayout
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_marginTop="5dp">

            <android.support.v4.view.ViewPager
                android:id="@+id/viewPager"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

            <LinearLayout
                android:background="#33000000"
                android:orientation="horizontal"
                android:layout_gravity="bottom"
                android:gravity="center_vertical"
                android:layout_width="match_parent"
                android:layout_height="35dip">
                <TextView
                    android:layout_weight="8"
                    android:id="@+id/tv_pager_title"
                    android:text="标题"
                    android:paddingLeft="8dip"
                    android:gravity="center_vertical"
                    android:textColor="@color/white"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"/>
                <!--用来动态添加轮播小点-->
                <LinearLayout
                    android:id="@+id/lineLayout_dot"
                    android:layout_weight="2"
                    android:gravity="center|right"
                    android:layout_marginRight="5dp"
                    android:paddingLeft="3dp"
                    android:paddingRight="3dp"
                    android:orientation="horizontal"
                    android:layout_width="0dp"
                    android:layout_height="match_parent">
                </LinearLayout>

            </LinearLayout>
        </FrameLayout>
相关标签: viewpager