IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> ViewPager实现轮播+轮播提示器(小点点) -> 正文阅读

[移动开发]ViewPager实现轮播+轮播提示器(小点点)

在这里插入图片描述
1

<RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">


        <androidx.viewpager.widget.ViewPager
            android:id="@+id/vp_home_frag_banner"
            android:layout_width="match_parent"
            android:layout_height="186dp"
            android:layout_marginLeft="13dp"
            android:layout_marginRight="13dp"
            android:layout_marginTop="17dp"
            android:background="@color/white"></androidx.viewpager.widget.ViewPager>

        <RadioGroup
            android:layout_marginBottom="8dp"
            android:id="@+id/rg_home_frag_banner"
            android:layout_width="wrap_content"
            android:layout_height="13dp"
            android:layout_centerHorizontal="true"
            android:layout_alignBottom="@id/vp_home_frag_banner"
            android:orientation="horizontal">

            <RadioButton
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:layout_weight="1"
                android:background="@drawable/slide_adv_selector"
                android:button="@null"
                android:clickable="false"/>

            <RadioButton
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:layout_weight="1"
                android:background="@drawable/slide_adv_selector"
                android:button="@null"
                android:clickable="false"/>

            <RadioButton
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:layout_weight="1"
                android:background="@drawable/slide_adv_selector"
                android:button="@null"
                android:clickable="false"/>

            <RadioButton
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:layout_weight="1"
                android:background="@drawable/slide_adv_selector"
                android:button="@null"
                android:clickable="false" />

            <RadioButton
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:layout_weight="1"
                android:background="@drawable/slide_adv_selector"
                android:button="@null"
                android:clickable="false" />

            <RadioButton
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:layout_weight="1"
                android:background="@drawable/slide_adv_selector"
                android:button="@null"
                android:clickable="false" />

            <RadioButton
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:layout_weight="1"
                android:background="@drawable/slide_adv_selector"
                android:button="@null"
                android:clickable="false" />

            <RadioButton
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:layout_weight="1"
                android:background="@drawable/slide_adv_selector"
                android:button="@null"
                android:clickable="false" />
        </RadioGroup>
    </RelativeLayout>

2

package com.ruhai.yibei.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.alibaba.fastjson.JSON;
import com.ruhai.yibei.Constant;
import com.ruhai.yibei.R;
import com.ruhai.yibei.activity.ServiceCustomActivity;
import com.ruhai.yibei.activity.ShopCustomActivity;
import com.ruhai.yibei.activity.YibeiHomeActivity;
import com.ruhai.yibei.activity.YibeiLineActivity;
import com.ruhai.yibei.adapter.HomeFragBannerAdapter;
import com.ruhai.yibei.bean.AnnouncementBean;
import com.ruhai.yibei.bean.BannerBean;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Timer;
import java.util.TimerTask;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;


public class HomeFragment extends Fragment implements ViewPager.OnPageChangeListener {
    private LinearLayout mTitleBar;
    private ImageSwitcher mImagSwitcher;
    private int[] imgIds;
    private ImageView shopCustom;
    private ImageView serviceCustom;
    private RelativeLayout rlYibeizaixian;
    private RelativeLayout rlYibeiHome;

    private ViewPager mVpHomeFragBanner;
    private int mBannerCount;
    private Timer mTimer;
    private boolean mVPCanPlay = true;
    private RadioGroup mRgHomeFragBanner;

    private TextSwitcher textSwitcher;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        imgIds = new int[]{R.mipmap.banner, R.mipmap.banner2};
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.e("wy", "onViewCreated: ");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTimer.cancel();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.e("wy", "onActivityCreated: ");
        mRgHomeFragBanner = (RadioGroup) getActivity().findViewById(R.id.rg_home_frag_banner);
        textSwitcher = (TextSwitcher) getActivity().findViewById(R.id.textSwitcher);
        textSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                TextView tv = new TextView(requireActivity());
                tv.setTextColor(Color.BLACK);
                return tv;
            }
        });

        RequestParams params = new RequestParams(Constant.announcement);
        params.addHeader("Authorization", Constant.authorization);
        params.addHeader("language", "zh_CN");
        params.setAsJsonContent(true);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onSuccess(String result) {
                AnnouncementBean professionInfo = JSON.parseObject(result, AnnouncementBean.class);
                Log.e("wy", "getTitle: " + professionInfo.getData().get(0).getTitle());

                if (professionInfo.getCode().equals("00000000")) {
                    Timer mTimer1 = new Timer();
                    final int[] j = {0};
                    mTimer1.schedule(new TimerTask() {
                        @Override
                        public void run() {
//                        mHandler.sendEmptyMessage(1);
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    j[0]++;
                                    if (j[0] >= professionInfo.getData().size() - 1) {
                                        j[0] = 0;
                                    }
                                    // Log.e("wy", "127getTitle: "+professionInfo.getData().get(j[0]).getTitle() );
                                    textSwitcher.setText(professionInfo.getData().get(j[0]).getTitle());
                                }
                            });
                        }
                    }, 0, 3000);


                } else {
                    Toast.makeText(x.app(), professionInfo.getMsg(), Toast.LENGTH_LONG).show();
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("wy", "result: " + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });


        mVpHomeFragBanner = (ViewPager) getActivity().findViewById(R.id.vp_home_frag_banner);
        //        监听用户是否接触banner,如果是则不轮播,否则轮播
        mVpHomeFragBanner.addOnPageChangeListener(this);


        mTitleBar = (LinearLayout) getActivity().findViewById(R.id.title_bar);
        setImmerseLayout(mTitleBar);

        mImagSwitcher = (ImageSwitcher) getActivity().findViewById(R.id.imageSwitcher);
        shopCustom = (ImageView) getActivity().findViewById(R.id.shop_custom);

        serviceCustom = (ImageView) getActivity().findViewById(R.id.service_custom);

        rlYibeizaixian = (RelativeLayout) getActivity().findViewById(R.id.rl_yibeizaixian);
        rlYibeiHome = (RelativeLayout) getActivity().findViewById(R.id.rl_yibei_home);

        RequestParams params1 = new RequestParams(Constant.bannerSite);
        params1.addHeader("Authorization", Constant.authorization);
        params1.addHeader("language", "zh_CN");
        params1.setAsJsonContent(true);
        params1.addBodyParameter("bannerSite", 1);


        x.http().get(params1, new Callback.CommonCallback<String>() {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onSuccess(String result) {
                BannerBean professionInfo = JSON.parseObject(result, BannerBean.class);

                if (professionInfo.getCode().equals("00000000")) {
//                    String picUrl = professionInfo.getData().get(0).getPicUrl();
//                    Log.e("wy", "onSuccess picUrl: " + picUrl);
//
                    mBannerCount = professionInfo.getData().size();
                    //轮播图在集合里,从中取出轮播图
                    mVpHomeFragBanner.setAdapter(new HomeFragBannerAdapter(professionInfo.getData(), getActivity()));
                    mVpHomeFragBanner.setCurrentItem(25000);
                    if (mTimer == null) {
                        mTimer = new Timer();
                        mTimer.schedule(new TimerTask() {
                            @Override
                            public void run() {
//                        mHandler.sendEmptyMessage(1);
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (mVPCanPlay) {
                                            mVpHomeFragBanner.setCurrentItem(mVpHomeFragBanner.getCurrentItem() + 1);
                                        }

                                    }
                                });
                            }
                        }, 3000, 3000);

                    }


                } else {
                    Toast.makeText(x.app(), professionInfo.getMsg(), Toast.LENGTH_LONG).show();
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("wy", "result: " + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });


        rlYibeizaixian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), YibeiLineActivity.class));

            }
        });
        rlYibeiHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), YibeiHomeActivity.class));

            }
        });
        shopCustom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), ShopCustomActivity.class));

            }
        });
        serviceCustom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), ServiceCustomActivity.class));

            }
        });


        if (mImagSwitcher != null) {
            mImagSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
                @Override
                public View makeView() {
                    // makeView返回的是当前需要显示的ImageView控件,用于填充进ImageSwitcher中
                    return new ImageView(getActivity());
                }
            });
        }
        if (mImagSwitcher != null) {
            mImagSwitcher.postDelayed(new Runnable() {
                int currentIndex = 0;

                @Override
                public void run() {
                    mImagSwitcher.setBackgroundResource(imgIds[currentIndex]);
//                    Log.e("wy", "mListString:" + imgIds[currentIndex]);
//                    Bitmap bit = BitmapFactory.decodeFile(imgIds[currentIndex]+"");
//                    Drawable drawable = new BitmapDrawable(bit);
//                    mImagSwitcher.setBackgroundDrawable(drawable);
                    if (currentIndex == (imgIds.length - 1))
                        currentIndex = 0;
                    else
                        currentIndex++;
                    mImagSwitcher.postDelayed(this, 3000);
                }
            }, 200);
        }

    }

    //获取沉浸式布局
    protected void setImmerseLayout(View view) {// view为标题栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getActivity().getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int statusBarHeight = getStatusBarHeight(getActivity().getBaseContext());
            view.setPadding(0, statusBarHeight, 0, 0);
        }
    }

    public int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }
    //    rudiobutton小点点和轮播图做关联,这是viewPager的监听
    @Override
    public void onPageSelected(int position) {
        Log.e("wy", "position: " + position + " mBannerCount:" + mBannerCount);
        if (mBannerCount != -1) {
            int realPos = position % mBannerCount;
            Log.e("wy", "onPageSelected: " + realPos);
            RadioButton childAt = (RadioButton) mRgHomeFragBanner.getChildAt(realPos);
            childAt.setChecked(true);
        }

    }

    @Override
    public void onPageScrollStateChanged(int state) {
//        判断轮播图是否被用户拖拽
        mVPCanPlay = state == ViewPager.SCROLL_STATE_IDLE;
    }
}

2.1分析:获取轮播图片,在viewPager中展示

 RequestParams params1 = new RequestParams(Constant.bannerSite);
        params1.addHeader("Authorization", Constant.authorization);
        params1.addHeader("language", "zh_CN");
        params1.setAsJsonContent(true);
        params1.addBodyParameter("bannerSite", 1);


        x.http().get(params1, new Callback.CommonCallback<String>() {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onSuccess(String result) {
                BannerBean professionInfo = JSON.parseObject(result, BannerBean.class);

                if (professionInfo.getCode().equals("00000000")) {
//                    String picUrl = professionInfo.getData().get(0).getPicUrl();
//                    Log.e("wy", "onSuccess picUrl: " + picUrl);
//
                    mBannerCount = professionInfo.getData().size();
                    //轮播图在集合里,从中取出轮播图
                    mVpHomeFragBanner.setAdapter(new HomeFragBannerAdapter(professionInfo.getData(), getActivity()));
                    mVpHomeFragBanner.setCurrentItem(25000);
                    if (mTimer == null) {
                        mTimer = new Timer();
                        mTimer.schedule(new TimerTask() {
                            @Override
                            public void run() {
//                        mHandler.sendEmptyMessage(1);
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (mVPCanPlay) {
                                            mVpHomeFragBanner.setCurrentItem(mVpHomeFragBanner.getCurrentItem() + 1);
                                        }

                                    }
                                });
                            }
                        }, 3000, 3000);

                    }


                } else {
                    Toast.makeText(x.app(), professionInfo.getMsg(), Toast.LENGTH_LONG).show();
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("wy", "result: " + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });

2.2

类要实现implements ViewPager.OnPageChangeListener

    //    rudiobutton小点点和轮播图做关联,这是viewPager的监听
    @Override
    public void onPageSelected(int position) {
        Log.e("wy", "position: " + position + " mBannerCount:" + mBannerCount);
        if (mBannerCount != -1) {
            int realPos = position % mBannerCount;
            Log.e("wy", "onPageSelected: " + realPos);
            RadioButton childAt = (RadioButton) mRgHomeFragBanner.getChildAt(realPos);
            childAt.setChecked(true);
        }

    }
  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-03-06 13:12:56  更:2022-03-06 13:14:12 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 16:32:46-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码