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

Android左右滑动切换图片

程序员文章站 2022-06-09 15:54:18
...

ImageUtils.java:

 

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;

/**  
 * @ClassName: ImageUtils  
 * @Description: 处理图片的工具类 
 * @author chenzheng
 * @date 2014-4-17 下午3:11:08  
 */
public class ImageUtils {

	/**
	 * 图片基准路径
	 */
	private static final String BASE_SDCARD_IMAGES = "/mnt/sdcard/weijie/images/";

	private static final String TAG = "ImageUtils";

	/**
	 * 判断文件是否存在
	 *
	 * @param 文件在本地的完整名
	 * @return
	 */
	private static boolean judgeExists(String fullName) {

		File file = new File(fullName);

		return file.exists();
	}

	/**
	 * 获取最后的‘/’后的文件名
	 *
	 * @param name
	 * @return
	 */
	private static String getLastName(String name) {
		int lastIndexOf = 0;
		try {
			lastIndexOf = name.lastIndexOf('/');
		} catch (Exception e) {
			e.printStackTrace();
		}
		return !name.equals("") ? name.substring(lastIndexOf + 1) : "";
	}

	/**
	 * 拼接一个完整的本地文件名
	 * @param 文件的网络路径
	 * @return
	 */
	private static String getImageFullName(String name) {
		return BASE_SDCARD_IMAGES + getLastName(name);
	}

	/**
	 * 通过该网络路径获取Bitmap
	 * @param 该图片的网络路径
	 */
	public static Bitmap getBitmap(String urlPath) {

		Bitmap bitmap = null;
		String fullName = getImageFullName(urlPath);
		if (ImageUtils.judgeExists(fullName)) {
			/* 存在就直接使用 */
			Log.i(TAG, "使用了sdcard里的图片");
			bitmap = BitmapFactory.decodeFile(fullName);
		} else {
			/* 去下载图片,下载完成之后返回该对象 */
			Log.i(TAG, "去下载了图片");
			bitmap = downloadAndSaveBitmap(urlPath, fullName);
		}
		return bitmap;
	}

	/**
	 * 下载保存图片
	 *
	 * @param urlPath
	 *            下载路径
	 * @param fullName
	 *            文件保存路径+文件名
	 * @return
	 */
	private static Bitmap downloadAndSaveBitmap(String urlPath, String fullName) {

		Bitmap bitmap = downloadImage(urlPath);

		/* 首先判断是否挂载了sdcard */
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {

			if (bitmap != null) {

				saveBitmap(fullName, bitmap);

			}
		} else {
			Log.e(TAG, "没有sdcard无法保存图片");
		}

		return bitmap;
	}

	/**
	 * 保存图片
	 *
	 * @param fullName
	 * @param bitmap
	 */
	private static void saveBitmap(String fullName, Bitmap bitmap) {

		if (bitmap != null) {

			try {
				File file = new File(fullName);
				if (!file.exists()) {
					creatFolder(fullName);
					file.createNewFile();
				}
				FileOutputStream fos = new FileOutputStream(file);
				bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
				fos.flush();
			} catch (IOException e) {
				e.printStackTrace();
				Log.e(TAG, "图片保存失败,异常信息是:" + e.toString());
			}
		} else {
			Log.e(TAG, "没有下载成功图片,无法保存");
		}
	}

	/**
	 * 创建保存文件的文件夹
	 *
	 * @param fullName
	 *            带文件名的文件路径
	 * @return
	 */
	private static void creatFolder(String fullName) {
		if (getLastName(fullName).contains(".")) {
			String newFilePath = fullName.substring(0, fullName
					.lastIndexOf('/'));
			File file = new File(newFilePath);
			file.mkdirs();
		}
	}

	/**
	 * 下载图片
	 *
	 * @param urlPath
	 * @return
	 */
	private static Bitmap downloadImage(String urlPath) {

		try {
			byte[] byteData = getImageByte(urlPath);
			if (byteData == null) {
				Log.e(TAG, "没有得到图片的byte,问题可能是path:" + urlPath);
				return null;
			}
			int len = byteData.length;

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inPreferredConfig = Bitmap.Config.RGB_565;
			options.inPurgeable = true;
			options.inInputShareable = true;
			options.inJustDecodeBounds = false;
			if (len > 200000) {// 大于200K的进行压缩处理
				options.inSampleSize = 2;
			}

			return BitmapFactory.decodeByteArray(byteData, 0, len);
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "图片下载失败,异常信息是:" + e.toString());
			return null;
		}
	}

	/**
	 * 获取图片的byte数组
	 *
	 * @param urlPath
	 * @return
	 */
	private static byte[] getImageByte(String urlPath) {
		InputStream in = null;
		byte[] result = null;
		try {
			URL url = new URL(urlPath);
			HttpURLConnection httpURLconnection = (HttpURLConnection) url
					.openConnection();
			httpURLconnection.setDoInput(true);
			httpURLconnection.connect();
			if (httpURLconnection.getResponseCode() == 200) {
				in = httpURLconnection.getInputStream();
				result = readInputStream(in);
				in.close();
			} else {
				Log
						.e(TAG, "下载图片失败,状态码是:"
								+ httpURLconnection.getResponseCode());
			}
		} catch (Exception e) {
			Log.e(TAG, "下载图片失败,原因是:" + e.toString());
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	/**
	 * 将输入流转为byte数组
	 *
	 * @param in
	 * @return
	 * @throws Exception
	 */
	private static byte[] readInputStream(InputStream in) throws Exception {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = in.read(buffer)) != -1) {
			baos.write(buffer, 0, len);
		}
		baos.close();
		in.close();
		return baos.toByteArray();

	}

	/**
	 * 此方法用来异步加载图片
	 * @param imageview
	 * @param path
	 */
	public static void downloadAsyncTask(final ImageView imageview,
			final String path) {
		new AsyncTask<String, Void, Bitmap>() {

			@Override
			protected Bitmap doInBackground(String... params) {
				return getBitmap(path);
			}

			@Override
			protected void onPostExecute(Bitmap result) {
				super.onPostExecute(result);
				if (result != null && imageview != null) {
					imageview.setImageBitmap(result);
				} else {
					Log.e(TAG, "在downloadAsyncTask里异步加载图片失败!");
				}
			}

		}.execute(new String[] {});

	}

}

 

 

 

 

 

ProductDetailIndex.java:

 

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

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.weijie.app_user.R;
import com.weijie.app_user.utility.ImageUtils;

public class ProductDetailIndex extends Activity {

	private ViewPager viewPager; // android-support-v4中的滑动组件
	private int default_bg=R.drawable.a;
	private List<ImageView> imageViews; // 滑动的图片集合

	private String[] imageResUrl; // 图片url
	private List<ImageView> dots; // 图片标题正文的那些点

	private int currentItem = 0; // 当前图片的索引号

	private Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			if (msg.what == 0) {
				@SuppressWarnings("unchecked")
				List<Bitmap> bmList=(List<Bitmap>) msg.obj;
				for(int i=0;i<bmList.size();i++){
					Bitmap bitmap=bmList.get(i);
					ImageView imageView = new ImageView(getApplicationContext());
					if (bitmap != null) {
						imageView.setImageBitmap(bitmap);
					} else {
						imageView.setImageResource(default_bg);
					}
					imageView.setScaleType(ScaleType.CENTER_CROP);
					imageViews.add(imageView);
				}
				
				viewPager = (ViewPager) findViewById(R.id.img_viewpager);
				viewPager.setAdapter(new MyPagerAdapter());// 设置填充ViewPager页面的适配器
				// 设置一个监听器,当ViewPager中的页面改变时调用
				viewPager.setOnPageChangeListener(new MyPageChangeListener());
			}
		};

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.product_detail_index);
		
		imageViews = new ArrayList<ImageView>();
		
		new Thread() {

			@SuppressWarnings("unchecked")
			public void run() {
				List<Bitmap> bitmapList = new ArrayList<Bitmap>();
				Message msg = new Message();
				Bitmap bitmap=null;
				imageResUrl = new String[] {
						"http://imgt8.bdstatic.com/it/u=2,1200870009&fm=19&gp=0.jpg",
						"http://imgt3.bdstatic.com/it/u=2483720495,3389680904&fm=21&gp=0.jpg",
						"http://imgt6.bdstatic.com/it/u=2,936516090&fm=19&gp=0.jpg" };
				for (int i = 0; i < imageResUrl.length; i++) {
					bitmap=ImageUtils.getBitmap(imageResUrl[i]);
					bitmapList.add(bitmap);
					
				}
				msg.what = 0;
				msg.obj = bitmapList;
				handler.sendMessage(msg);
			}

		}.start();
		
		dots = new ArrayList<ImageView>();  
        dots.add((ImageView) findViewById(R.id.v_dot1));  
        dots.add((ImageView) findViewById(R.id.v_dot2));  
        dots.add((ImageView) findViewById(R.id.v_dot3)); 
        dots.get(currentItem).setImageResource(R.drawable.orange_btn); 
	}



	/**
	 * 填充ViewPager页面的适配器
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyPagerAdapter extends PagerAdapter {

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

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(imageViews.get(arg1));
			return imageViews.get(arg1);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

		@Override
		public void finishUpdate(View arg0) {

		}
	}

	/**
	 * 当ViewPager中页面的状态发生改变时调用
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyPageChangeListener implements OnPageChangeListener {
		private int oldPosition = 0;

		public void onPageSelected(int position) {
			currentItem = position;
			dots.get(oldPosition).setImageResource(R.drawable.white_btn);  
            dots.get(position).setImageResource(R.drawable.orange_btn); 
			oldPosition = position;
		}

		public void onPageScrollStateChanged(int arg0) {

		}

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

		}
	}

}

 

 

 

 

 

product_detail_index.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:background="@color/orange"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/header_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:src="@drawable/reg_back" />
        <!-- 商品详情 -->

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@id/header_back"
            android:text="商品详情"
            android:textColor="@color/white"
            android:textSize="24sp" />

        <ImageView
            android:id="@+id/three_dot"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="10dp"
            android:src="@drawable/shop_threedot" />

        <LinearLayout
            android:id="@+id/goods_share"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_toLeftOf="@id/three_dot"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/goods_share" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="分享"
                android:textColor="@color/white"
                android:textSize="14sp" />
        </LinearLayout>
    </RelativeLayout>

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="240dp" >

        <android.support.v4.view.ViewPager
            android:id="@+id/img_viewpager"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_gravity="bottom"  
            android:layout_marginBottom="8dp"
            android:orientation="horizontal" >
            <ImageView
                android:id="@+id/v_dot1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/white_btn" />
            <ImageView
                android:id="@+id/v_dot2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:src="@drawable/white_btn" />
            <ImageView
                android:id="@+id/v_dot3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/white_btn" />
        </LinearLayout>
    </FrameLayout>

</LinearLayout>

 

相关标签: ViewPager