1. 程式人生 > >Android實現圖片輪播效果

Android實現圖片輪播效果

註明:轉載請註明本文連結

MainActivity.java

package com.example.carr.advertisement;

import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
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;

public class MainActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private TextView tv_title;
    private boolean is_state = false;
    private LinearLayout point_ll;
    private ArrayList<ImageView> imageViews;

    //點
    ImageView point;
    //記錄上一次的位置
    private int perPoint = 0;

    //圖片陣列
    private final int IMAGES[] = {R.drawable.x0, R.drawable.xa, R.drawable.xb, R.drawable.xc, R.drawable.xd, R.drawable.xe};

    //標題陣列
    private final String TITLES[] = {"勇於創新", "探索求精", "程式碼狂人", "用程式碼點亮世界", "科技發展未來", "年薪30萬"};

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);

        //查詢控制元件
        viewPager = findViewById(R.id.viewpager);
        tv_title = findViewById(R.id.title);
        point_ll = findViewById(R.id.point_ll);

        imageViews = new ArrayList<>();
        for (int i = 0; i < IMAGES.length; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setBackgroundResource(IMAGES[i]);
            imageViews.add(imageView);

            //新增點
            point = new ImageView(this);
            point.setBackgroundResource(R.drawable.point_red);

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(32, 32);
            if (i == 0) {
                //如果為true點的顏色是紅色
                point.setEnabled(true);
                tv_title.setText(TITLES[0]);
            } else {
                params.leftMargin = 8;
                //為false點的顏色是灰色
                point.setEnabled(false);
            }
            point.setLayoutParams(params);
            point_ll.addView(point);
        }

        viewPager.setAdapter(new MyAdapter());

        //監聽ViewPager頁面更改
        viewPager.addOnPageChangeListener(new MyOnPageChangeListener());

        int item=Integer.MAX_VALUE/2 - Integer.MAX_VALUE/2%imageViews.size();
        viewPager.setCurrentItem(item);

        handler.sendEmptyMessageDelayed(0,3000);
    }

    //圖片輪播
    class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            int relPosition = position%imageViews.size();
            ImageView imageView = imageViews.get(relPosition);
            container.addView(imageView);
            imageView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    switch (motionEvent.getAction()){
                        case MotionEvent.ACTION_DOWN:
                            handler.removeCallbacksAndMessages(null);
                            break;
                        case MotionEvent.ACTION_MOVE:
                            break;
                        case MotionEvent.ACTION_UP:
                            handler.removeCallbacksAndMessages(null);
                            handler.sendEmptyMessageDelayed(0,3000);
                            break;
                    }
                    return true;
                }
            });
            return imageView;
        }

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

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

    //控制點
    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

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

        }

        @Override
        public void onPageSelected(int position) {
            int relPosition = position%imageViews.size();
            //設定文字
            tv_title.setText(TITLES[relPosition]);

            //設定點顏色為灰色
            point_ll.getChildAt(perPoint).setEnabled(false);

            //設定點的顏色為紅色
            point_ll.getChildAt(relPosition).setEnabled(true);

            //獲取上一次的位置
            perPoint = relPosition;
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if(state == ViewPager.SCROLL_STATE_DRAGGING){
                is_state =true;
                handler.removeCallbacksAndMessages(null);
            }else if(state == ViewPager.SCROLL_STATE_IDLE){
                is_state=false;
                handler.removeCallbacksAndMessages(null);
                handler.sendEmptyMessageDelayed(0,3000);
            }else if(state == ViewPager.SCROLL_STATE_SETTLING){

            }
        }
    }
}
layout_main.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:orientation="vertical">

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

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

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#ffffff"
            android:padding="5dp"
            android:gravity="center_horizontal"
            android:text="美國隊長3"/>

        <LinearLayout
            android:id="@+id/point_ll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_gravity="center_horizontal">

        </LinearLayout>
    </LinearLayout>

</RelativeLayout>