Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> 自定義圖片輪播,簡單就是好用,自定義圖片輪播

自定義圖片輪播,簡單就是好用,自定義圖片輪播

編輯:關於android開發

自定義圖片輪播,簡單就是好用,自定義圖片輪播


圖片輪播是一種常見的自定義控件,也有多種實現的方法,這裡提供一種簡單的ViewPager實現的案例。

實現功能:圖片循環輪播,進度顯示,圖片點擊事件

實現只需三步:

1 添加類文件到項目中。

2 在xml布局中引入標簽。

3 實例化並設置簡單參數。

具體使用方法,詳見代碼注釋。

==================================================================

自定義java文件

package com.dashou.viewpagerimage;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* 自定義圖片輪播控件
* 使用方法:
* 1 在xml布局中引入本包名,並設置ID,代碼類中實例化此類對象。
* 2 通過setViewPager()方法設置參數(int size, List<Map<String, Object>> list)
*   size是輪播圖片的數量,list需要存入圖片的url地址
* 3 設置此控件的監聽事件
* 注意:Demo使用xutils請求網絡
* Created by dashou on 2016/3/23.
*/
public class MyViewPager extends RelativeLayout implements View.OnTouchListener, ViewPager.OnPageChangeListener {

    private ViewPager viewPager;
    //放置圓點圖片的布局
    private LinearLayout image;
    //設置圖片填充方式
    public ImageView.ScaleType setScaleType = ImageView.ScaleType.FIT_XY;
    //存儲圖片url以及點擊事件需要的id等數據
    private List<Map<String, Object>> list;
    private OnViewPagerClickListener onViewPagerClickListener;
    private int num;
    private int index_img = 0;
    public long time = 3000;//設置循環間隔時間
    private boolean isContinue = true;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            index_img++;
            viewPager.setCurrentItem(index_img);
        }
    };

    public MyViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    /**
     * 初始化控件
     */
    private void init() {
        viewPager = new ViewPager(getContext());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        addView(viewPager, lp);
        image = new LinearLayout(getContext());
        image.setOrientation(LinearLayout.HORIZONTAL);
        image.setGravity(Gravity.CENTER_VERTICAL);
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(200, 50);
        rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        rlp.addRule(RelativeLayout.CENTER_HORIZONTAL);
        addView(image, rlp);
    }

    /**
     * 設置ViewPager
     */
    public void setViewPager(int size, List<Map<String, Object>> list) {
        this.list = list;
        num = size;
        addDots(size);
        List<View> views = new ArrayList<View>();
        for (int i = 0; i < size; i++) {
            ImageView img = new ImageView(getContext());
            img.setScaleType(setScaleType);
            views.add(img);
        }
        MyViewPagerAdapter adapter = new MyViewPagerAdapter(getContext(), views);
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(this);
        viewPager.setOnTouchListener(this);
        startContinue();
    }

    /**
     * 添加進度顯示
     *
     * @param size
     */
    private void addDots(int size) {
        for (int i = 0; i < size; i++) {
            LinearLayout.LayoutParams dot_lp=new LinearLayout.LayoutParams(5,30);
            dot_lp.width=0;
            dot_lp.weight = 1.0f;
            TextView tv = new TextView(getContext());
            if (i==0){
                tv.setText(i+1+"");
                tv.setTextColor(Color.RED);
            }else {
                tv.setText(i+1+"");
                tv.setTextColor(Color.BLUE);
            }
            image.addView(tv,dot_lp);
        }
    }

    //重置圖片狀態按鈕
    private void resetDots(int id){
        for (int i = 0; i < list.size(); i++) {
            ((TextView)(image.getChildAt(i))).setTextColor(Color.BLUE);
        }
        ((TextView)(image.getChildAt(id))).setTextColor(Color.RED);
    }
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                isContinue = false;
                break;
            case MotionEvent.ACTION_UP:
                isContinue = true;
                break;
            default:
                isContinue = true;
                break;
        }
        return false;
    }

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

    }

    @Override
    public void onPageSelected(int position) {
        index_img = position;
        resetDots(position%list.size());
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    //圖片點擊事件對外接口
    interface OnViewPagerClickListener {
        /**
         * 圖片點擊事件監聽
         * @param position 對應被點擊的圖片
         */
        void OnViewPager(int position);
    }
    //初始化接口方法
    public void setOnViewPagerClickListener(OnViewPagerClickListener onViewPagerClickListener) {
        this.onViewPagerClickListener = onViewPagerClickListener;
    }

    //啟動線程循環播放圖片
    private void startContinue() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                while (viewPager!=null) {
                    try {
                        sleep(time);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (isContinue){
                        Message msg = Message.obtain();
                        msg.what = 0;
                        handler.sendMessage(msg);
                    }
                }
            }
        }.start();
    }

    /**
     * ViewPager適配器
     */
    class MyViewPagerAdapter extends PagerAdapter {
        private final List<View> views;
        private ImageOptions imageOptions = new ImageOptions.Builder()
                .build();

        public MyViewPagerAdapter(Context context, List<View> views) {
            this.views = views;
        }

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

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

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            final int mposition = position%views.size();
            View view = views.get(mposition);
            ViewPager viewPager = (ViewPager) container;
            if (view instanceof ImageView) {
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //調用MyViewPager裡的接口
                        if (onViewPagerClickListener!=null){
                            onViewPagerClickListener.OnViewPager(mposition);
                        }
                    }
                });
            }
            //使用加載圖片
            x.image().bind((ImageView) view, list.get(mposition).get("url").toString(), imageOptions);
            viewPager.addView(view);
            return view;
        }

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

===============================================================

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">

    <com.dashou.viewpagerimage.MyViewPager
        android:id="@+id/myViewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </com.dashou.viewpagerimage.MyViewPager>
</RelativeLayout>

====================================================================

Activity代碼

package com.dashou.viewpagerimage;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ContentView(R.layout.activity_main)
public class MainActivity extends Activity implements MyViewPager.OnViewPagerClickListener {

    //實例化控件********注意此Demo使用xutils請求
    @ViewInject(R.id.myViewPager)
    private MyViewPager myViewPager;
    private String[] img_url = {"http://3p.pic.ttdtweb.com/3p.ttpod.com/singer/110/6697838.jpg",
            "http://3p.pic.ttdtweb.com/3p.ttpod.com/singer/110/1439024.jpg",
            "http://3p.pic.ttdtweb.com/3p.ttpod.com/singer/110/1439025.jpg",
            "http://3p.pic.ttdtweb.com/3p.ttpod.com/singer/110/1439021.jpg",
            "http://3p.pic.ttdtweb.com/3p.ttpod.com/singer/110/1439020.jpg",
            "http://3p.pic.ttdtweb.com/3p.ttpod.com/singer/110/1439022.jpg",
            "http://3p.pic.ttdtweb.com/3p.ttpod.com/singer/110/1439023.jpg"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setMyViewPager();
    }

    private void setMyViewPager() {
        //准備list資源
        List<Map<String, Object>> views_list = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < img_url.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("url", img_url[i]);
            views_list.add(map);
        }
        //需要兩個參數 1. 數量 2.url地址list
        myViewPager.setViewPager(img_url.length, views_list);
        myViewPager.setOnViewPagerClickListener(this);
    }

    @Override
    public void OnViewPager(int position) {
        //這裡實現圖片點擊後的操作
        int id = position+1;
        Toast.makeText(this,"第"+id+"張圖片被點擊了",Toast.LENGTH_SHORT).show();
    }
}

======================================================

結束

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved