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

Android轮播图,代码全,已经实现,欢迎私信

程序员文章站 2022-08-12 15:25:53
Android轮播图逻辑代码布局文件代码逻辑代码package com.example.viewpager;import android.annotation.SuppressLint;import android.os.Handler;import android.os.Message;import android.support.annotation.NonNull;import android.support.v4.view.PagerAdapter;import android.su...

Android轮播图

逻辑代码

package com.example.viewpager;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;

@SuppressLint(“HandlerLeak”)
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private TextView tv_title;
private LinearLayout ll_point_group;
private ArrayList imageViews;
//图片资源id
private final int[] imageIds = {
R.mipmap.chaxun,
R.mipmap.jiaoxue,
R.mipmap.kebiao,
R.mipmap.music,
R.mipmap.student
};
//上一次高亮显示的位置
private int prePosition = 0;

private boolean isDragging = false;
//图片标题集合
private final String[] imageDescription =
        {
                "哈喽1",
                "hello2",
                "hello3",
                "hello4",
                "hello5"
        };
//是否已经滚动
private boolean isScroll = false;
private Handler handler = new Handler() {
    @Override
    public void handleMessage(@NonNull Message msg) {
        super.handleMessage(msg);
        int item = viewPager.getCurrentItem() + 1;
        viewPager.setCurrentItem(item);
        //延迟4s发送消息
        handler.sendEmptyMessageDelayed(0, 4000);

    }
};


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    viewPager = findViewById(R.id.viewpager);
    tv_title = findViewById(R.id.tv_title);
    ll_point_group = findViewById(R.id.ll_point_group);

    //准备数据
    imageViews = new ArrayList<>();
    for (int i = 0; i < imageIds.length; i++) {
        ImageView imageView = new ImageView(this);
        imageView.setBackgroundResource(imageIds[i]);//可以来自网络
        //添加到集合中
        imageViews.add(imageView);

        //添加点击
        ImageView point = new ImageView(this);
        point.setBackgroundResource(R.drawable.point_selector);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(18, 18);

        if (i == 0) {
            point.setEnabled(true);//显示红色
        } else {
            point.setEnabled(false);
            params.leftMargin = 18;
        }

        point.setLayoutParams(params);

        ll_point_group.addView(point);

    }
    viewPager.setAdapter(new MyPageAdapter());

//设置监听viewpager页面变化
viewPager.addOnPageChangeListener(new MyOnPageChangeListener());
//设置中间位置
int item = Integer.MAX_VALUE / 2 - Integer.MAX_VALUE % imageViews.size();//要保证imaggeview的整数倍
viewPager.setCurrentItem(item);

    tv_title.setText(imageDescription[0]);
    //发消息
    handler.sendEmptyMessageDelayed(0, 3000);
}

class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

    /**
     * 当页面滚动或者滑动的时候回调
     *
     * @param i  当前页面位置
     * @param v  滑动页面的百分比
     * @param i1 再屏幕上滑动的像素
     */
    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    /**
     * 当某个页面被选中的时候调用
     *
     * @param i 被选中的页面的位置
     */
    @Override
    public void onPageSelected(int i) {
        int realPosition = i % imageViews.size();

//吧上一个高亮的设置为默认,当前设置为高亮,
// //设置对应页面的文本信息
tv_title.setText(imageDescription[realPosition]);
ll_point_group.getChildAt(prePosition).setEnabled(false);
ll_point_group.getChildAt(realPosition).setEnabled(true);
prePosition = realPosition;
}

    /**
     * 当页面滚动状态变化的时候回调
     * 静止->滑动
     * 滑动—_>静止
     *
     * @param i
     */
    @Override
    public void onPageScrollStateChanged(int i) {
        if (i == ViewPager.SCROLL_STATE_SETTLING) {

        } else if (i == ViewPager.SCROLL_STATE_IDLE && isDragging) {
            //空闲
            isDragging = false;

            handler.removeCallbacksAndMessages(null);
            handler.sendEmptyMessageDelayed(0, 3000);

        } else if (i == ViewPager.SCROLL_STATE_DRAGGING) {
            //拖拽
            isDragging = true;
            handler.removeCallbacksAndMessages(null);
        }
    }
}

class MyPageAdapter extends PagerAdapter implements View.OnTouchListener, View.OnClickListener {
    /**
     * 得到图片总数
     *
     * @return
     */
    @Override
    public int getCount() {
        //return imageViews.size();
        return Integer.MAX_VALUE;
    }

    /**
     * 相当于getView方法
     * @param container viewpager 自身
     * @param position  当前实例化页面得位置
     * @return
     */
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        int realPosition = position % imageViews.size();
        ImageView imageView = imageViews.get(realPosition);
        container.addView(imageView);//添加到viewpager中
        imageView.setTag(position);
        imageView.setOnTouchListener(this);
        imageView.setOnClickListener(this);
        return imageView;
    }

    /**
     * 释放资源
     *
     * @param container viewpager
     * @param position  释放的位置
     * @param object    释放的页面
     */
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        //super.destroyItem(container, position, object);
        container.removeView((View) object);
    }

    /**
     * 比较view跟object是否同一个实例
     *
     * @param view 页面
     * @param o    instantiateItem返回的结果
     * @return
     */
    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN://按下
                handler.removeCallbacksAndMessages(null);
                Log.d("TAG", "onTouch: 手指按下");
                break;
            case MotionEvent.ACTION_MOVE://手机再控件上移动
                break;
            case MotionEvent.ACTION_UP://离开
                Log.e("TAG", "onTouch: 手指离开");
                handler.removeCallbacksAndMessages(null);
                handler.sendEmptyMessageDelayed(0, 3000);
                break;
        }
        return false;
    }

    @Override
    public void onClick(View view) {
        Log.e("TAG", "onClick: 点击事件");
        int position = (int) view.getTag()%imageViews.size();
        String text=imageDescription[position];
        Toast.makeText(MainActivity.this,text,Toast.LENGTH_LONG).show();
    }
}

}

布局文件代码

由RelativeLayout,ViewPager,LinearLayout,构成。下面展示 代码片.

// An highlighted block
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="180dp"

        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#44000000"
        android:padding="5dp"
        android:layout_alignBottom="@+id/viewpager"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="3dp"
            android:text="美人鱼"
            android:textColor="#ffffff" />

        <LinearLayout
            android:id="@+id/ll_point_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_gravity="center_horizontal"></LinearLayout>
    </LinearLayout>
</RelativeLayout>
## 选择器文件代码
###point_selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/point_normal" android:state_enabled="false" />
    <item android:drawable="@drawable/point_press" android:state_enabled="true" />
</selector>

###point_normal
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size
        android:width="16dp"
        android:height="16dp" />
    <solid android:color="#44000000" />
</shape>
###point_press
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <size android:height="16dp" android:width="16dp"/>
    <solid android:color="#ff0000"/>
</shape>

本文地址:https://blog.csdn.net/qq_37855976/article/details/107934532