安卓轮播图,无限自动轮播,可手动滑动+点击事件

                                                                        

一.结构

由ViewPager,和简单的自定义PagerAdapter构成,ScheduledExecutorService实现自动循环。

二.代码

1.XML

主页

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:background="#000000">
    </android.support.v4.view.ViewPager>
    <LinearLayout
        android:id="@+id/bottom_layout"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#33000000"
        android:orientation="vertical"
        android:layout_alignBottom="@+id/viewpager">
        <LinearLayout
            android:id="@+id/dos_layout"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:gravity="center">

        </LinearLayout>
    <TextView
        android:id="@+id/title_textview"
        android:layout_width="match_parent"
        android:textColor="#ffffff"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_gravity="center"
        android:gravity="center"/>
    </LinearLayout>
</RelativeLayout>

其中ViewPager用来放置图片,LinearLayout用来放置小圆点和图标标题。

另外附上两个小圆点的资源

dot_focused

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#000000"/>
</shape>

dot_normal

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#ffffff"/>
</shape>

2.JAVA

首先是自定义适配器,在内部声明了一个放置图片的数组

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.util.ArrayList;

public class MyPagerAdapter extends PagerAdapter {
    private Context context;
    private ArrayList<ImageView> imageViews;

    public MyPagerAdapter(Context context,ArrayList<ImageView>imageViews){
        this.context = context;
        this.imageViews = imageViews;
    }
    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        ImageView imageView = imageViews.get(position%imageViews.size());
        container.addView(imageView);
        return imageView;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((ImageView) object);
    }
}

activity完成代码

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.adefault.banner.R;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class BannerTwoActivity extends AppCompatActivity implements View.OnClickListener {
    private ViewPager viewPager;
    private ArrayList<ImageView> imageViews;

    private LinearLayout dos_layout;
    private ArrayList<TextView>textViews;
    private TextView textView;
    private int[] imageIds =new int[]{
            R.drawable.a,
            R.drawable.b,
            R.drawable.c,
            R.drawable.d,
            R.drawable.e,
    };
    private String[] titles = new String[]{
            "第一张图片",
            "第二张图片",
            "第三张图片",
            "第四张图片",
            "第五张图片",
    };

    private ScheduledExecutorService scheduledExecutorService;
    private int currentItem = 1;
    private int oldItem = 0;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bannertwo);
        bindViews();
        initData();
        setAdapter();
    }

    private void bindViews() {
        viewPager = (ViewPager)findViewById(R.id.viewpager);
        viewPager.setOnClickListener(this);
        textView = (TextView)findViewById(R.id.title_textview);
        textView.setText(titles[0]);
        dos_layout = (LinearLayout)findViewById(R.id.dos_layout);
    }

    private void initData() {
        imageViews = new ArrayList<ImageView>();
        textViews = new ArrayList<TextView>();
        for (int i = 0;i < imageIds.length;i++){
            ImageView imageView = new ImageView(this);
            imageView.setBackgroundResource(imageIds[i]);
            imageView.setOnClickListener(this);
            imageViews.add(imageView);
            TextView textView = new TextView(this);
            textView.setBackgroundResource(R.drawable.dot_normal);
            if (i == 0){
                textView.setBackgroundResource(R.drawable.dot_focused);
            }
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.height = 20;
            layoutParams.width = 20;
            layoutParams.setMargins(5,0,5,0);
            textView.setLayoutParams(layoutParams);
            textViews.add(textView);
            dos_layout.addView(textView);
        }
    }

    private void setAdapter() {
        MyPagerAdapter pagerAdapter = new MyPagerAdapter(this,imageViews);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override//选中某一页的监听
            public void onPageSelected(int i) {
                TextView currentTextView = textViews.get(i%textViews.size());
                TextView oldTextView = textViews.get(oldItem);
                currentTextView.setBackgroundResource(R.drawable.dot_focused);
                oldTextView.setBackgroundResource(R.drawable.dot_normal);
                oldItem = i%textViews.size();
                currentItem = i;
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(
                new ViewPageTask(),
                2,
                2,
                TimeUnit.SECONDS
        );
    }

    @Override
    public void onClick(View view) {
        int index = viewPager.getCurrentItem()%imageIds.length;
        Message message = new Message();
        Bundle bundle = new Bundle();
        bundle.putInt("index",index);
        message.setData(bundle);
        message.what = 1;
        handler.sendMessage(message);
        Log.e("胖虎","点击了:"+index);
    }

    //图片轮播任务
    private class ViewPageTask implements Runnable{
        @Override
        public void run() {
            handler.sendEmptyMessage(0);
        }
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0){
                viewPager.setCurrentItem(currentItem);
                textView.setText(titles[(currentItem)%titles.length]);
                currentItem += 1;
            }else {
                Bundle bundle = msg.getData();
                int index = bundle.getInt("index");
            }
        };
    };

    @Override
    protected void onStop() {
        super.onStop();
        if (scheduledExecutorService != null){
            scheduledExecutorService.shutdown();
            scheduledExecutorService = null;
        }
    }
}

完整demo下载

猜你喜欢

转载自blog.csdn.net/weixin_39339407/article/details/83749022