Viewpager图片自动轮播,网络图片加载,图片自动刷新

package com.teffy.viewpager;

import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends Activity {
    private ViewPager mViewPager;
    private ViewPagerAdapter adapter;
    String[] urls = new String[] {
            "http://img4.imgtn.bdimg.com/it/u=3741386655,1614062939&fm=21&gp=0.jpg",
            "http://img1.imgtn.bdimg.com/it/u=112648096,582309873&fm=23&gp=0.jpg",
            "http://photocdn.sohu.com/20120213/Img334596783.jpg",
            "http://pic11.nipic.com/20101210/2531170_111449179301_2.jpg",
            "http://www.foto8.net/files/201004/27/d272194910.jpg",
            "http://www.sootuu.com/photo/UploadFile/2006-4/20064304138937.jpg",
            "http://www.itxtbook.com/attachment/Day_081022/23_163307_e9b4513a7afee66.jpg",
            "http://img7.mypsd.com.cn/20120821/Mypsd_13920_201208211752500005B.jpg"
    };
    private ArrayList<View> dots = new ArrayList<View>();
    private int oldPosition = 0;//记录上一次点的位置
    private int currentItem; //当前页面
    private ScheduledExecutorService scheduledExecutorService;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mViewPager = (ViewPager) findViewById(R.id.vp_guanggao);
        mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                dots.get(oldPosition).setBackgroundResource(R.drawable.dxt_point_nomral);
                dots.get(position).setBackgroundResource(R.drawable.dxt_point_selected);
                oldPosition = position;
                currentItem = position;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
         initDots();    
        adapter = new ViewPagerAdapter(this,urls);
        mViewPager.setAdapter(adapter);
        vpChangeTask();
    }


    private void initDots() {
        LinearLayout ll_vp_point = (LinearLayout) findViewById(R.id.ll_vp_point);
        for (int i = 0; i <urls.length; i++) {
            ImageView iv_image = (ImageView) getLayoutInflater().inflate(R.layout.item_dots, null);
            if(i ==0){
                iv_image.setBackgroundResource(R.drawable.dxt_point_selected);
            }
            iv_image.setTag(urls[i]);
            ll_vp_point.addView(iv_image);
            dots.add(iv_image);
        }
    }

    private void vpChangeTask() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), 2,3, TimeUnit.SECONDS);
    }
    // 切换图片
    private class ViewPagerTask implements Runnable {
        @Override
        public void run() {
            currentItem = (currentItem + 1) %urls.length;
            mHandler.obtainMessage().sendToTarget();
        }
    }
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mViewPager.setCurrentItem(currentItem);
        }
    };
}
View Code
package com.teffy.viewpager;

import com.teffy.viewpager.AsyncImageLoader.ImageCallBack;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;


public  class ViewPagerAdapter extends PagerAdapter {
    Context context;

    String[] urls;
    LayoutInflater    layoutInflater ;
    AsyncImageLoader asyncImageLoader;
    public ViewPagerAdapter(Context context,String[] urls) {
        this.context=context;
        this.urls=urls;
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        asyncImageLoader=new AsyncImageLoader();
    }

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

    @Override
    public int getCount() {
        return urls.length;
    }

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

    @Override
    public Object instantiateItem(final View view, int position) {
        final String imgUrl = urls[position];
        final View imageLayout = layoutInflater.inflate(R.layout.item_pager_image, null);
        final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
        final ProgressBar progressBar = (ProgressBar) imageLayout.findViewById(R.id.loading);
        imageView.setTag(imgUrl);
        // 如果联网
        if (UtilTool.checkConnection(context)) {
            Bitmap bmpFromSD = FileCache.getInstance().getBmp(imgUrl);
            if (null != bmpFromSD) {
                imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, bmpFromSD.getHeight()));
                imageView.setImageBitmap(bmpFromSD);
                progressBar.setVisibility(View.INVISIBLE);
            } else {
                Drawable cachedImage = asyncImageLoader.loaDrawable(imgUrl,new ImageCallBack() {
                            @SuppressWarnings("unused")
                            @Override
                            public void imageLoaded(Drawable imageDrawable) {
                                Bitmap bitmap = UtilTool.drawToBmp(imageDrawable);
                                FileCache.getInstance().savaBmpData(imgUrl, bitmap);// 先缓存起来
//                                FileCache.getInstance().savaBmpData(view.getTag().toString(), bitmap);// 先缓存起来
                                ImageView imageViewByTag = null;
                                if (null != bitmap) {
                                    imageViewByTag = (ImageView) imageView.findViewWithTag(imgUrl);
                                    imageViewByTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,bitmap.getHeight()));
                                }
                                if (imageViewByTag != null) {
                                    if (true) {
                                        imageViewByTag.setImageBitmap(bitmap);
                                        progressBar.setVisibility(View.INVISIBLE);
                                    } else {
                                        if (bitmap != null) {
                                            imageViewByTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
                                            imageViewByTag.setImageBitmap(bitmap);
                                            imageViewByTag.setScaleType(ImageView.ScaleType.MATRIX);
                                            progressBar.setVisibility(View.INVISIBLE);
                                        }
                                    }
                                }
                            }
                        });
                if (cachedImage == null) {
                    imageView.setImageResource(R.drawable.ic_launcher);
                } else {
                    if (UtilTool.isWifi(context)) {
                        Bitmap bitmap = UtilTool.drawToBmp(cachedImage);
                        imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,bitmap.getHeight()));
                        imageView.setImageBitmap(bitmap);
                    } else {
                        imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
                        Bitmap bitmap = UtilTool.drawToBmp(cachedImage);
                        imageView.setImageBitmap(bitmap);
                        progressBar.setVisibility(View.INVISIBLE);
                    }
                }
            }
        } else {
            Bitmap bmpFromSD = FileCache.getInstance().getBmp(imgUrl);
            if (null != bmpFromSD) {
                ImageView imageViewByTag = (ImageView) imageView.findViewWithTag(imgUrl);
                imageViewByTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,bmpFromSD.getHeight()));
                imageViewByTag.setImageBitmap(bmpFromSD);
            } else {
                imageView.setImageResource(R.drawable.ic_launcher);
                progressBar.setVisibility(View.GONE);
            }
        }
        ((ViewPager) view).addView(imageLayout, 0);
        return imageLayout;
    }
}
View Code
package com.teffy.viewpager;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class UtilTool {
    /**
     * Drawable转换成Bitmap
     * @param d
     * @return
     */
    public static Bitmap drawToBmp(Drawable d) {
        if (null != d) {
            BitmapDrawable bd = (BitmapDrawable) d;
            return bd.getBitmap();
        }
        return null;
    }

    /**
     * 检测网络连接
     * 
     * @return
     */
    public static boolean checkConnection(Context context) {
        @SuppressWarnings("static-access")
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null) {
            return networkInfo.isAvailable();
        }
        return false;
    }

    /**
     * Wifi是否可用
     * @param mContext
     * @return
     */
    public static boolean isWifi(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null && activeNetInfo.getTypeName().equals("WIFI")) {
            return true;
        }
        return false;
    }
}
View Code
package com.teffy.viewpager;

import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

public class AsyncImageLoader {

    public Map<String, SoftReference<Drawable>> imageCache;

    public AsyncImageLoader() {
        imageCache = new HashMap<String, SoftReference<Drawable>>();
    }

    public Drawable loaDrawable(final String imageUrl, final ImageCallBack imageCallBack) {
        Bitmap bmpFromSD = FileCache.getInstance().getBmp(imageUrl);
        if (null != bmpFromSD) {
            return new BitmapDrawable(bmpFromSD);
        }
        if (imageCache.containsKey(imageUrl)) {
            SoftReference<Drawable> softReference = imageCache.get(imageUrl);
            Drawable drawable = softReference.get();
            if (null != drawable) {
                return drawable;
            }
        }

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message message) {
                imageCallBack.imageLoaded((Drawable) message.obj);
            }
        };

        new Thread() {
            @Override
            public void run() {
                Drawable drawable = loadImageFromUrl(imageUrl);
                imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                Message message = handler.obtainMessage(0, drawable);
                handler.sendMessage(message);
            }
        }.start();
        return null;
    }
    /**
     * 下载图片
     * @param url
     * @return
     */
    public Drawable loadImageFromUrl(String url) {
        URL tempUrl;
        InputStream inputStream = null;
        Drawable drawable = null;

        try {
            tempUrl = new URL(url);
            
            inputStream = (InputStream) tempUrl.getContent();
            
//            BitmapFactory.Options o = new BitmapFactory.Options();
//            o.inJustDecodeBounds =true;
//            BitmapFactory.decodeStream(inputStream);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            drawable = Drawable.createFromStream(inputStream, "src");
        } catch (OutOfMemoryError err) {
            System.out.println("内存溢出...");
        }

        return drawable;
    }

    public interface ImageCallBack {
        public void imageLoaded(Drawable imageDrawable);
    }

}
View Code
package com.teffy.viewpager;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

public class FileCache {

    private static FileCache fileCache; // 本类的引用
    private String strImgPath; // 图片保存的路径
    private String strJsonPath;// Json保存的路径

    private FileCache() {
        String strPathHead = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            strPathHead = Environment.getExternalStorageDirectory().toString();
        } else{
            strPathHead = "/data/data/com.teffy.viewpager";
        }
        strImgPath = strPathHead + "/vp/images/";
        strJsonPath = strPathHead + "/vp/json/";
    }

    public static FileCache getInstance() {
        if (null == fileCache) {
            fileCache = new FileCache();
        }
        return fileCache;
    }

    public boolean saveData(String strApiUrl, String dataJson,String imgurl, Bitmap bmp) {
        String fileName = this.toHexString(strApiUrl);
        String imgName = imgurl.substring(
                imgurl.lastIndexOf('/') + 2,
                imgurl.length());
        File jsonFile = new File(strJsonPath);
        File imgFile = new File(strImgPath);
        if (!jsonFile.exists()) {
            jsonFile.mkdirs();
        }
        if (!imgFile.exists()) {
            imgFile.mkdirs();
        }
        File fTXT = new File(strJsonPath + fileName + ".txt");
        File fImg = new File(strImgPath + imgName);
        this.writeToFile(dataJson, fTXT);
        this.writeToFile(bmp, fImg);
        return true;
    }

    /**
     * 保存json数据
     * */
    public boolean savaJsonData(String strApiUrl, String dataJson) {
        String fileName = this.toHexString(strApiUrl);
        File jsonFile = new File(strJsonPath);
        if (!jsonFile.exists()) {
            jsonFile.mkdirs();
        }
        File fTXT = new File(strJsonPath + fileName + ".txt");
        if (fTXT.exists()) {
            fTXT.delete();
        }
        this.writeToFile(dataJson, fTXT);
        return true;
    }

    // 用图片的URL来命名图片,并保存图片
    public boolean savaBmpData(String imgurl, Bitmap bmp) {
        String imgName = imgurl.substring(
                imgurl.lastIndexOf('/') + 2,
                imgurl.length());
        File imgFileDirs = new File(strImgPath);
        if (!imgFileDirs.exists()) {
            imgFileDirs.mkdirs();
        }
        File fImg = new File(strImgPath + imgName);
        if (fImg.exists()) {
            fImg.delete();
        }
        this.writeToFile(bmp, fImg);
        return true;
    }

    // 自己给图片命名并保存图片
    public boolean saveBmpDataByName(String bmpName, Bitmap bmp) {
        File imgFileDirs = new File(strImgPath);
        if (!imgFileDirs.exists()) {
            imgFileDirs.mkdirs();
        }
        File fImg = new File(strImgPath + bmpName);
        if (fImg.exists()) {
            fImg.delete();
        }
        this.writeToFile(bmp, fImg);
        return true;
    }

    /**
     * 
     * 参数fileName需与 fileName和saveData()方法中的fileName参数一致时,才能读出与保存时一致的数据
     * 
     * */
    public String getJson(String strApiUrl) {
        String fileName = this.toHexString(strApiUrl);
        File file = new File(strJsonPath + fileName + ".txt");
        StringBuffer sb = new StringBuffer();
        if (file.exists()) {
            Reader reader = null;
            try {
                reader = new java.io.FileReader(file);
                BufferedReader br = new BufferedReader(reader);
                String str;
                while (null != (str = br.readLine())) {
                    sb.append(str);
                }
                return sb.toString();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 传入图片的URL地址,来获得Bitmap
     * */
    public Bitmap getBmp(String imgurl) {
        
        String imgName = imgurl.substring(
                imgurl.lastIndexOf('/') + 2,
                imgurl.length());

        File imgFile = new File(strImgPath + imgName);
        if (imgFile.exists()) {
            FileInputStream fis;
            try {
                fis = new FileInputStream(imgFile);
                return BitmapFactory.decodeStream(fis);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else
            Log.v("提醒", "要请求的图片文件不存在");
        return null;
    }

    // 通过图片名字来获得图片
    public Bitmap getBmpByName(String bmpName) {
        File imgFile = new File(strImgPath + bmpName);
        if (imgFile.exists()) {
            FileInputStream fis;
            try {
                fis = new FileInputStream(imgFile);
                return BitmapFactory.decodeStream(fis);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            Log.v("提醒", "要请求的图片文件不存在");
        }
        return null;
    }

    /**
     * 传入图片的URL来获得图片文件
     * */
    public File getImgFile(String imgurl) {
        String imgName = imgurl.substring(
                imgurl.lastIndexOf('/') + 2,
                imgurl.length());
        File imgFile = new File(strImgPath + imgName);
        return imgFile;
    }

    private boolean writeToFile(String strData, File file) {
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bos.write(strData.getBytes());
            bos.flush();
            bos.close();
            return true;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    private boolean writeToFile(Bitmap bmp, File file) {
        if (file.exists()) {
            file.delete();
        }
        String name = file.getName();
        String geShi = name.substring(name.lastIndexOf('.'), name.length());

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            if (null != bmp) {
                if (".JPEG".equalsIgnoreCase(geShi)
                        || ".JPG".equalsIgnoreCase(geShi)) {
                    bmp.compress(CompressFormat.JPEG, 100, bos);
                    bos.flush();
                    bos.close();
                } else if (".PNG".equalsIgnoreCase(geShi)) {
                    bmp.compress(CompressFormat.PNG, 100, bos);
                    bos.flush();
                    bos.close();
                }
                return true;
            } else
                bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.v("错误", "图片写入缓存文件错误");
                }
            }
        }
        return false;
    }

    public boolean clearImgByImgUrl(String imgurl) {
        File imgFile = this.getImgFile(imgurl);
        if (imgFile.exists()) {
            imgFile.delete();
            return true;
        }
        return false;
    }

    /**
     * 删除SD卡上的全部缓存
     * */
    public int clearAllData() {
        File imgDir = new File(strImgPath);
        File txtDir = new File(strJsonPath);
        File[] imgFiles = imgDir.listFiles();
        File[] txtFiles = txtDir.listFiles();
        int m = imgFiles.length;
        int x = txtFiles.length;

        int g = 0;
        int t = 0;
        for (int i = 0; i < m; i++) {
            if (imgFiles[i].exists()) {
                if (imgFiles[i].delete())
                    g++;
            } else
                g++;

        }
        for (int i = 0; i < x; i++) {
            if (txtFiles[i].exists()) {
                if (txtFiles[i].delete()) {
                    t++;
                }
            } else
                t++;
        }
        if (g == m && t == x) {
            return 1;
        }
        return 0;
    }
    private String toHexString(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return "0x" + str;// 0x表示十六进制
    }

    // 转换十六进制编码为字符串
    private String toStringHex(String s) {
        if ("0x".equals(s.substring(0, 2))) {
            s = s.substring(2);
        }
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(
                        s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "utf-8");// UTF-16le:Not
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }
}
View Code

 源码下载 :链接: http://pan.baidu.com/s/1i3sradv 

posted on 2014-06-11 17:56  clarenceV1  阅读(1292)  评论(3编辑  收藏  举报

导航