Android利用Gallery和ImageSwitcher实现在线相册图片预览功能(异步加载图片)

Android利用Gallery和ImageSwitcher实现相册功能(异步加载图片)


MainActivity.java

package cn.android.gallery;

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageView;
import cn.android.service.ImageLoader;
import cn.android.widget.LoadingViewHandler;

/**
 * 应用入口程序
 * @Description MainActivity

 * @File MainActivity.java

 * @Package cn.android.gallery

 * @Author WanTianwen

 * @Blog  http://blog.csdn.net/WanTianwen

 * @Date 2014-04-13

 * @Version V1.0
 */
public class MainActivity extends Activity {
	private int goodsId;

    GoodsListGalleryAdapter adapter; 
    private ArrayList<HashMap<String, String>> goodsGalleryList;
        
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.goods_detail);
		
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		goodsId = 99999;//商品ID可以通过意图传值过来
		
		String server = getString(R.string.server);
		String url = server + "getGoodsDetail";
		String params = "goods_id="+goodsId;
		
		GetGoodsDataTask task = new GetGoodsDataTask(this);
		task.execute(server, url, params);
	}

	class GetGoodsDataTask extends AsyncTask<String, Integer, JSONObject> {
		private Activity mActivity;
		private String mServer;
		public GetGoodsDataTask(Activity activity) {
			mActivity = activity;
		}
		/**
		 * 处理后台执行的任务,在后台线程执行
		 */
		@Override
		protected JSONObject doInBackground(String... params) {
			mServer = params[0];
			try {//这里面可以通过网络获取json格式的数据
				return new JSONObject("{\"result\":1,\"data\":{\"goods_detail\":{\"cat_id\":\"8\",\"goods_sn\":\"YL14040207\",\"goods_size\":\"S,M,L,XL,XXL XXXL\",\"shop_price\":\"102.00\",\"goods_material\":\"Polyester\",\"goods_id\":\"99999\",\"goods_name\":\"Glaring Beads O-Neck Floral Print Short Sleeve Sheath Dress\",\"goods_color\":\"Orange,Green\",\"goods_thumb\":\"images/201404/02/201404020959jsd.jpg\",\"goods_weight\":\"300.00\"},\"goods_gallery\":[{\"medium_url\":\"gallery/201404/02/m201404020959wbc.jpg\",\"thumb_url\":\"gallery/201404/02/s201404020959wbc.jpg\",\"img_original\":\"gallery/201404/02/201404020959wbc.jpg\"},{\"medium_url\":\"gallery/201404/02/m201404020959zxi.jpg\",\"thumb_url\":\"gallery/201404/02/s201404020959zxi.jpg\",\"img_original\":\"gallery/201404/02/201404020959zxi.jpg\"},{\"medium_url\":\"gallery/201404/02/m201404020959skv.jpg\",\"thumb_url\":\"gallery/201404/02/s201404020959skv.jpg\",\"img_original\":\"gallery/201404/02/201404020959skv.jpg\"},{\"medium_url\":\"gallery/201404/02/m201404020959sjr.jpg\",\"thumb_url\":\"gallery/201404/02/s201404020959sjr.jpg\",\"img_original\":\"gallery/201404/02/201404020959sjr.jpg\"},{\"medium_url\":\"gallery/201404/02/m201404020959fle.jpg\",\"thumb_url\":\"gallery/201404/02/s201404020959fle.jpg\",\"img_original\":\"gallery/201404/02/201404020959fle.jpg\"}],\"count\":1},\"msg\":\"ok\"}");
			} catch (Exception e) {
				return null;
			}
		}

		/**
		 * 后台任务执行完之后被调用,在UI线程执行
		 */
		protected void onPostExecute(JSONObject jsonObject) {
			if (jsonObject != null) {
				try {
					int resultCode = jsonObject.getInt("result");
					if (1 == resultCode) {
						JSONObject dataObject = jsonObject.getJSONObject("data");
						//获取返回数目
						int count = dataObject.getInt("count");
						if (count>0) {
							goodsGalleryList = new ArrayList<HashMap<String, String>>();
							
							JSONObject goodsDetail = dataObject.getJSONObject("goods_detail");
							
							//获取返回新闻集合
							JSONArray newslist = dataObject.getJSONArray("goods_gallery");
							for(int i=0;i<newslist.length();i++) {
								
								JSONObject newsObject = (JSONObject)newslist.opt(i); 
								HashMap<String, String> hashMap = new HashMap<String, String>();
								hashMap.put("thumb_url", mServer + "uploads/" + newsObject.getString("thumb_url"));
								hashMap.put("medium_url", mServer + "uploads/" + newsObject.getString("medium_url"));
								hashMap.put("img_original", mServer + "uploads/" + newsObject.getString("img_original"));
								goodsGalleryList.add(hashMap);
							}
							
							
							Gallery gallery = (Gallery) findViewById(R.id.goods_gallery);
							adapter = new GoodsListGalleryAdapter(mActivity, goodsGalleryList);          
						    gallery.setAdapter(adapter); 
						    gallery.setSelection(1);
						    
						    gallery.setOnItemClickListener(new OnItemClickListener() {
						        public void onItemClick(AdapterView parent, View v, int position, long id) {
						            Intent intent = new Intent();
						            intent.putExtra("position", position);
						            intent.putExtra("mGoodsGalleryList", goodsGalleryList);
						            intent.setClass(getApplicationContext(), GoodsGalleryActivity.class);
						            startActivityForResult(intent, 100);
						        }
						    });
						}
						else {
							//加上自己的业务处理
						}
					}
					else {
						//加上自己的业务处理
					}
				} catch(Exception e) {
					e.printStackTrace();
				}
				
			} else {
				//获取图片失败
			}
			LoadingViewHandler.dismiss();
		}

		/**
		 * 在 doInBackground(Params...)之前被调用,在UI线程执行
		 */
		protected void onPreExecute() {
			LoadingViewHandler.creteProgressDialog(mActivity, "");
		}
	}
	
	class GoodsListGalleryAdapter extends BaseAdapter {  
	    private Activity activity;  
	    private ArrayList<HashMap<String, String>> data;  
	    public ImageLoader imageLoader;
	      
	    public GoodsListGalleryAdapter(Activity act, ArrayList<HashMap<String, String>> dat) { 
	        activity = act;  
	        data = dat; 
	        imageLoader = new ImageLoader(activity.getApplicationContext());  
	    }  
	  
	    public int getCount() {  
	        return data.size();  
	    }  
	  
	    public Object getItem(int position) {  
	        return position;  
	    }  
	  
	    public long getItemId(int position) {  
	        return position;  
	    }  
	      
	    public View getView(int position, View convertView, ViewGroup parent) {  
	        ImageView vi = new ImageView(activity);
	        HashMap<String, String> hashMap = new HashMap<String, String>();
	        hashMap = data.get(position);
	        imageLoader.DisplayImage(hashMap.get("thumb_url"), vi);

	        vi.setAdjustViewBounds(true);
	        vi.setLayoutParams((new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)));
	        vi.setScaleType(ImageView.ScaleType.FIT_XY);
	        return vi;  
	    }  
	}
}


GoodsGalleryActivity.java

package cn.android.gallery;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import cn.android.service.ImageLoader;
import cn.android.widget.LoadingViewHandler;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewSwitcher;

/**
 * 相册展示应用程序
 * @Description GoodsGalleryActivity

 * @File GoodsGalleryActivity.java

 * @Package cn.android.gallery

 * @Author WanTianwen

 * @Blog  http://blog.csdn.net/WanTianwen

 * @Date 2014-04-13

 * @Version V1.0
 */
public class GoodsGalleryActivity  extends Activity implements
AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {
	private TextView titlebarTitle;
	private ImageView navigationBackButton;
	private Gallery galleyImages;
	private int position;
	private float startX;
	private FrameLayout switcherFrame;
	private ImageSwitcher imageSwitcher;
	public ImageLoader imageLoader;
	private ArrayList<HashMap<String, String>> goodsGalleryList;
	private LinearLayout commonError;
    
    @SuppressWarnings("unchecked")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.goods_gallery);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = (int)(display.getWidth()); //设置宽度
        getWindow().setAttributes(lp);

        
        Intent intent = getIntent();
        int position = intent.getIntExtra("position", 0);
        goodsGalleryList = (ArrayList<HashMap<String, String>>) intent.getSerializableExtra("mGoodsGalleryList");
        
        commonError = (LinearLayout) findViewById(R.id.common_error);
        
        titlebarTitle = (TextView) findViewById(R.id.titlebar_title);
        //mTitlebarTitle.setText("1/" + 5);
		navigationBackButton = (ImageView) findViewById(R.id.navigation_back_button);
		navigationBackButton.setOnClickListener(new NavigationBackButtonListener(this));
		
        imageSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
        imageSwitcher.setFactory(this);
        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in));
        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out));
        switcherFrame = (FrameLayout) findViewById(R.id.switcher_frame);
        switcherFrame.setOnTouchListener(new MSwitcherOnTouchListener(this));

        galleyImages = (Gallery) findViewById(R.id.goods_gallery);
        galleyImages.setAdapter(new ImageAdapter(this));
        galleyImages.setOnItemSelectedListener(this);
        galleyImages.setSelection(position);
    }

    @SuppressWarnings("rawtypes")
	public void onItemSelected(AdapterView parent, View v, int position, long id) {
    	position = position;
		try {
	    	GetImageTask task = new GetImageTask(this);
			task.execute(goodsGalleryList.get(position).get("medium_url"));
	        titlebarTitle.setText((position + 1) + " / " + goodsGalleryList.size());
	        imageSwitcher.setVisibility(View.VISIBLE);
		} catch (Exception e) {
			commonError.setVisibility(View.VISIBLE);
	        imageSwitcher.setVisibility(View.GONE);
		}  
    }

    @SuppressWarnings("rawtypes")
	public void onNothingSelected(AdapterView parent) {
    }

    public View makeView() {
        ImageView i = new ImageView(this);
        i.setScaleType(ImageView.ScaleType.FIT_CENTER);
        i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT));
        return i;
    }

    public class ImageAdapter extends BaseAdapter {
    	private Context mContext;
        public ImageAdapter(Context c) {
            mContext = c;
            imageLoader = new ImageLoader(c);
        }

        public int getCount() {
            return goodsGalleryList.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
        	ImageView vi = new ImageView(mContext);
            HashMap<String, String> hashMap = new HashMap<String, String>();
            hashMap = goodsGalleryList.get(position);
            imageLoader.DisplayImage(hashMap.get("thumb_url"), vi);
            vi.setAdjustViewBounds(true);
            vi.setLayoutParams((new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)));
            vi.setScaleType(ImageView.ScaleType.FIT_XY);
            vi.setBackgroundResource(R.drawable.detail);
            return vi; 
        }
    }

    private class NavigationBackButtonListener implements OnClickListener {
		private Activity activity;
		public NavigationBackButtonListener(Activity activity) {
			this.activity = activity;
		}
		@Override
		public void onClick(View v) {
			activity.finish();
		}
	}
    private class MSwitcherOnTouchListener implements OnTouchListener {
    	private Activity activity;
    	public MSwitcherOnTouchListener(Activity activity) {
    		this.activity = activity;
    	}

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch(event.getAction()) {
			//手指按下
			case MotionEvent.ACTION_DOWN:
				//记录起始坐标
				startX = event.getX();
				break;
			//手指抬起
			case MotionEvent.ACTION_UP:
				if(event.getX() != startX) {
					if(event.getX() < startX && position < goodsGalleryList.size() - 1) {
						position++;
					}
					if(event.getX() > startX && position > 0) {
						position--;
					}
					galleyImages.setSelection(position);
				} else {
					activity.finish();//单击关闭该窗口
				}
				break;
			}
			return true;
		}
    	
    }
    
    @SuppressWarnings("unused")
	private OnTouchListener mSwitcherOnTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch(event.getAction()) {
			//手指按下
			case MotionEvent.ACTION_DOWN:
				//记录起始坐标
				startX = event.getX();
				break;
			//手指抬起
			case MotionEvent.ACTION_UP:
				if(event.getX() < startX && position < goodsGalleryList.size()) {
					position++;
				}
				if(event.getX() > startX && position > 0) {
					position--;
				}
				galleyImages.setSelection(position);
				break;
			}
			return true;
		}
	};
	
	
	class GetImageTask extends AsyncTask<String, Integer, Bitmap> {
		private Activity mActivity;
		public GetImageTask(Activity activity) {
			mActivity = activity;
		}
		/**
		 * 处理后台执行的任务,在后台线程执行
		 */
		@Override
		protected Bitmap doInBackground(String... params) {
			Bitmap bitmap;
			try {
				URL picUrl = new URL(params[0]);
				HttpURLConnection urlConn;
				urlConn = (HttpURLConnection) picUrl.openConnection();
				urlConn.setConnectTimeout(5000);
				urlConn.setReadTimeout(5000);
				InputStream is = urlConn.getInputStream();
				bitmap = BitmapFactory.decodeStream(is);
				is.close();
			} catch (Exception e) {
				return null;
			}
			return bitmap;
		}

		/**
		 * 在调用publishProgress之后被调用,在UI线程执行
		 */
		protected void onProgressUpdate(Integer... progress) {
			//mProgressBar.setProgress(progress[0]);// 更新进度条的进度
		}

		/**
		 * 后台任务执行完之后被调用,在UI线程执行
		 */
		protected void onPostExecute(Bitmap result) {
			if (result != null) {
				Drawable drawable = new BitmapDrawable(result);
				imageSwitcher.setImageDrawable(drawable);
			} else {
				//获取图片网络失败
			}
			LoadingViewHandler.dismiss();
		}

		/**
		 * 在 doInBackground(Params...)之前被调用,在UI线程执行
		 */
		protected void onPreExecute() {
			LoadingViewHandler.creteProgressDialog(mActivity, "");
		}

		/**
		 * 在UI线程执行
		 */
		protected void onCancelled() {
		}
	}
}

goods_detail.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:orientation="vertical" android:id="@id/details_layout" android:background="@color/white" android:layout_width="fill_parent" android:layout_height="fill_parent"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <RelativeLayout android:id="@id/detail_layout" android:background="@drawable/tab_bar_bg" android:layout_width="fill_parent" android:layout_height="wrap_content">
        <ImageView android:id="@id/navigation_back_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/back_btn" android:layout_centerVertical="true" />
        <ImageView android:id="@id/separator_line" android:layout_width="2.0dip" android:layout_height="wrap_content" android:src="@drawable/navigation_separator_line" android:layout_toRightOf="@id/navigation_back_button" />
        <TextView android:textSize="18.0dip" android:textColor="@color/white" android:ellipsize="end" android:gravity="center" android:id="@id/detail_header_label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/app_name" android:singleLine="true" android:layout_centerInParent="true" />
        <ImageView android:id="@id/add_to_cart" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/featured_productbasic_cart_btn" android:layout_alignParentRight="true" />
        <TextView android:textSize="9.0sp" android:gravity="center" android:id="@id/tv_cart_count" android:background="@drawable/quantity_circle" android:paddingLeft="5.0dip" android:paddingRight="5.0dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="1.0dip" android:layout_marginRight="10.0dip" android:text="0" android:singleLine="true" android:layout_alignTop="@id/detail_layout" android:layout_alignRight="@id/add_to_cart" />
    </RelativeLayout>
    <Gallery android:gravity="left" android:id="@id/goods_gallery" android:tag="mygallery" android:layout_width="fill_parent" android:layout_height="80.0dip" android:layout_marginTop="5.0dip" android:layout_marginBottom="1.0dip" android:spacing="5.0dip" android:layout_below="@id/detail_layout" />
</RelativeLayout>

goods_gallery.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#90000000">
	<RelativeLayout 
	    	android:id="@id/titlebar_layout"
	    	android:layout_width="match_parent"
    		android:layout_height="wrap_content">
    	<ImageView android:id="@id/navigation_back_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/back_btn" android:layout_centerVertical="true" />
        <ImageView android:id="@id/navigation_separator" android:layout_width="2.0dip" android:layout_height="wrap_content" android:src="@drawable/navigation_separator_line" android:layout_toRightOf="@id/navigation_back_button" />
	    <TextView 
	        android:id="@id/titlebar_title"
	    	android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:layout_centerInParent="true"
    		android:textSize="12.0sp"
    		android:layout_marginTop="9.0dip"
    		android:layout_marginLeft="10.0dip"
    		android:textColor="@color/white"
    		android:text="@string/app_name"/>
	</RelativeLayout>
	<FrameLayout
	    android:id="@id/switcher_frame"
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent">
	    <ImageSwitcher
	        android:id="@id/switcher"
	        android:layout_width="match_parent"
	        android:layout_height="match_parent"
	        android:layout_gravity="center" />
		<LinearLayout
		    android:id="@id/common_error"
			android:layout_width="wrap_content"
		    android:layout_height="wrap_content"
		    android:orientation="vertical"
		    android:layout_gravity="center"
		    android:visibility="gone">
		    <ImageView 
		        android:layout_width="wrap_content"
		        android:layout_height="wrap_content"
		        android:layout_gravity="center"
		        android:src="@drawable/notwork_be_illogical" />
		    <TextView 
		        android:id="@id/message"
		        android:layout_width="wrap_content"
		    	android:layout_height="wrap_content"
		        android:text="@string/network_disconnected"
		        android:layout_gravity="center"
		        android:textColor="@color/white"/>
		</LinearLayout>
	</FrameLayout>

    <Gallery
        android:id="@id/goods_gallery"
        android:layout_width="fill_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:gravity="center_vertical"
        android:spacing="16dp" />
</RelativeLayout>

loading.xml

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

效果图





下载地址:http://download.csdn.net/detail/wantianwen/7191777

Android利用Gallery和ImageSwitcher实现在线相册图片预览功能(异步加载图片),,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。