Android圖片上傳,可以選擇多張圖片,縮放預覽,拍照上傳等

仿照微信,朋友圈分享圖片功能 。可以進行圖片的多張選擇,拍照添加圖片,以及進行圖片的預覽,預覽時可以進行縮放,並且可以刪除選中狀態的圖片 。很不錯的源碼,大家有需要可以下載看看 。

微信

微信

微信

微信

微信

微信

微信

微信

下載地址 : 微信上傳圖片源碼

//部分代碼如下

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.king.photo.activity;  
  2.    
  3. import android.annotation.SuppressLint;  
  4. import android.app.Activity;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.graphics.Bitmap;  
  8. import android.graphics.BitmapFactory;  
  9. import android.graphics.Color;  
  10. import android.graphics.drawable.BitmapDrawable;  
  11. import android.graphics.drawable.ColorDrawable;  
  12. import android.os.Bundle;  
  13. import android.os.Handler;  
  14. import android.os.Message;  
  15. import android.provider.MediaStore;  
  16. import android.util.Log;  
  17. import android.view.Gravity;  
  18. import android.view.KeyEvent;  
  19. import android.view.LayoutInflater;  
  20. import android.view.View;  
  21. import android.view.View.OnClickListener;  
  22. import android.view.ViewGroup;  
  23. import android.view.ViewGroup.LayoutParams;  
  24. import android.view.animation.AnimationUtils;  
  25. import android.widget.AdapterView;  
  26. import android.widget.AdapterView.OnItemClickListener;  
  27. import android.widget.BaseAdapter;  
  28. import android.widget.Button;  
  29. import android.widget.GridView;  
  30. import android.widget.ImageView;  
  31. import android.widget.LinearLayout;  
  32. import android.widget.PopupWindow;  
  33. import android.widget.RelativeLayout;  
  34.    
  35. import com.king.photo.R;  
  36. import com.king.photo.util.Bimp;  
  37. import com.king.photo.util.FileUtils;  
  38. import com.king.photo.util.ImageItem;  
  39. import com.king.photo.util.PublicWay;  
  40. import com.king.photo.util.Res;  
  41.    
  42.    
  43.    
  44.  //首頁面activity  
  45.    
  46. public class MainActivity extends Activity {  
  47.    
  48.     private GridView noScrollgridview;  
  49.     private GridAdapter adapter;  
  50.     private View parentView;  
  51.     private PopupWindow pop = null;  
  52.     private LinearLayout ll_popup;  
  53.     public static Bitmap bimap ;  
  54.       
  55.     protected void onCreate(Bundle savedInstanceState) {  
  56.         super.onCreate(savedInstanceState);  
  57.         Res.init(this);  
  58.         bimap = BitmapFactory.decodeResource(  
  59.                 getResources(),  
  60.                 R.drawable.icon_addpic_unfocused);  
  61.         PublicWay.activityList.add(this);  
  62.         parentView = getLayoutInflater().inflate(R.layout.activity_selectimg, null);  
  63.         setContentView(parentView);  
  64.         Init();  
  65.     }  
  66.    
  67.     public void Init() {  
  68.           
  69.         pop = new PopupWindow(MainActivity.this);  
  70.           
  71.         View view = getLayoutInflater().inflate(R.layout.item_popupwindows, null);  
  72.    
  73.         ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);  
  74.           
  75.         pop.setWidth(LayoutParams.MATCH_PARENT);  
  76.         pop.setHeight(LayoutParams.WRAP_CONTENT);  
  77.         pop.setBackgroundDrawable(new BitmapDrawable());  
  78.         pop.setFocusable(true);  
  79.         pop.setOutsideTouchable(true);  
  80.         pop.setContentView(view);  
  81.           
  82.         RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);  
  83.         Button bt1 = (Button) view  
  84.                 .findViewById(R.id.item_popupwindows_camera);  
  85.         Button bt2 = (Button) view  
  86.                 .findViewById(R.id.item_popupwindows_Photo);  
  87.         Button bt3 = (Button) view  
  88.                 .findViewById(R.id.item_popupwindows_cancel);  
  89.         parent.setOnClickListener(new OnClickListener() {  
  90.               
  91.             @Override  
  92.             public void onClick(View v) {  
  93.                 // TODO Auto-generated method stub  
  94.                 pop.dismiss();  
  95.                 ll_popup.clearAnimation();  
  96.             }  
  97.         });  
  98.         bt1.setOnClickListener(new OnClickListener() {  
  99.             public void onClick(View v) {  
  100.                 photo();  
  101.                 pop.dismiss();  
  102.                 ll_popup.clearAnimation();  
  103.             }  
  104.         });  
  105.         bt2.setOnClickListener(new OnClickListener() {  
  106.             public void onClick(View v) {  
  107.                 Intent intent = new Intent(MainActivity.this,  
  108.                         AlbumActivity.class);  
  109.                 startActivity(intent);  
  110.                 overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);  
  111.                 pop.dismiss();  
  112.                 ll_popup.clearAnimation();  
  113.             }  
  114.         });  
  115.         bt3.setOnClickListener(new OnClickListener() {  
  116.             public void onClick(View v) {  
  117.                 pop.dismiss();  
  118.                 ll_popup.clearAnimation();  
  119.             }  
  120.         });  
  121.           
  122.         noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);    
  123.         noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));  
  124.         adapter = new GridAdapter(this);  
  125.         adapter.update();  
  126.         noScrollgridview.setAdapter(adapter);  
  127.         noScrollgridview.setOnItemClickListener(new OnItemClickListener() {  
  128.    
  129.             public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
  130.                     long arg3) {  
  131.                 if (arg2 == Bimp.tempSelectBitmap.size()) {  
  132.                     Log.i("ddddddd""----------");  
  133.                     ll_popup.startAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.activity_translate_in));  
  134.                     pop.showAtLocation(parentView, Gravity.BOTTOM, 00);  
  135.                 } else {  
  136.                     Intent intent = new Intent(MainActivity.this,  
  137.                             GalleryActivity.class);  
  138.                     intent.putExtra("position""1");  
  139.                     intent.putExtra("ID", arg2);  
  140.                     startActivity(intent);  
  141.                 }  
  142.             }  
  143.         });  
  144.    
  145.     }  
  146.    
  147.     @SuppressLint("HandlerLeak")  
  148.     public class GridAdapter extends BaseAdapter {  
  149.         private LayoutInflater inflater;  
  150.         private int selectedPosition = -1;  
  151.         private boolean shape;  
  152.    
  153.         public boolean isShape() {  
  154.             return shape;  
  155.         }  
  156.    
  157.         public void setShape(boolean shape) {  
  158.             this.shape = shape;  
  159.         }  
  160.    
  161.         public GridAdapter(Context context) {  
  162.             inflater = LayoutInflater.from(context);  
  163.         }  
  164.    
  165.         public void update() {  
  166.             loading();  
  167.         }  
  168.    
  169.         public int getCount() {  
  170.             if(Bimp.tempSelectBitmap.size() == 9){  
  171.                 return 9;  
  172.             }  
  173.             return (Bimp.tempSelectBitmap.size() + 1);  
  174.         }  
  175.    
  176.         public Object getItem(int arg0) {  
  177.             return null;  
  178.         }  
  179.    
  180.         public long getItemId(int arg0) {  
  181.             return 0;  
  182.         }  
  183.    
  184.         public void setSelectedPosition(int position) {  
  185.             selectedPosition = position;  
  186.         }  
  187.    
  188.         public int getSelectedPosition() {  
  189.             return selectedPosition;  
  190.         }  
  191.    
  192.         public View getView(int position, View convertView, ViewGroup parent) {  
  193.             ViewHolder holder = null;  
  194.             if (convertView == null) {  
  195.                 convertView = inflater.inflate(R.layout.item_published_grida,  
  196.                         parent, false);  
  197.                 holder = new ViewHolder();  
  198.                 holder.image = (ImageView) convertView  
  199.                         .findViewById(R.id.item_grida_image);  
  200.                 convertView.setTag(holder);  
  201.             } else {  
  202.                 holder = (ViewHolder) convertView.getTag();  
  203.             }  
  204.    
  205.             if (position ==Bimp.tempSelectBitmap.size()) {  
  206.                 holder.image.setImageBitmap(BitmapFactory.decodeResource(  
  207.                         getResources(), R.drawable.icon_addpic_unfocused));  
  208.                 if (position == 9) {  
  209.                     holder.image.setVisibility(View.GONE);  
  210.                 }  
  211.             } else {  
  212.                 holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position).getBitmap());  
  213.             }  
  214.    
  215.             return convertView;  
  216.         }  
  217.    
  218.         public class ViewHolder {  
  219.             public ImageView image;  
  220.         }  
  221.    
  222.         Handler handler = new Handler() {  
  223.             public void handleMessage(Message msg) {  
  224.                 switch (msg.what) {  
  225.                 case 1:  
  226.                     adapter.notifyDataSetChanged();  
  227.                     break;  
  228.                 }  
  229.                 super.handleMessage(msg);  
  230.             }  
  231.         };  
  232.    
  233.         public void loading() {  
  234.             new Thread(new Runnable() {  
  235.                 public void run() {  
  236.                     while (true) {  
  237.                         if (Bimp.max == Bimp.tempSelectBitmap.size()) {  
  238.                             Message message = new Message();  
  239.                             message.what = 1;  
  240.                             handler.sendMessage(message);  
  241.                             break;  
  242.                         } else {  
  243.                             Bimp.max += 1;  
  244.                             Message message = new Message();  
  245.                             message.what = 1;  
  246.                             handler.sendMessage(message);  
  247.                         }  
  248.                     }  
  249.                 }  
  250.             }).start();  
  251.         }  
  252.     }  
  253.    
  254.     public String getString(String s) {  
  255.         String path = null;  
  256.         if (s == null)  
  257.             return "";  
  258.         for (int i = s.length() - 1; i > 0; i++) {  
  259.             s.charAt(i);  
  260.         }  
  261.         return path;  
  262.     }  
  263.    
  264.     protected void onRestart() {  
  265.         adapter.update();  
  266.         super.onRestart();  
  267.     }  
  268.    
  269.     private static final int TAKE_PICTURE = 0x000001;  
  270.    
  271.     public void photo() {  
  272.         Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
  273.         startActivityForResult(openCameraIntent, TAKE_PICTURE);  
  274.     }  
  275.    
  276.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  277.         switch (requestCode) {  
  278.         case TAKE_PICTURE:  
  279.             if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) {  
  280.                   
  281.                 String fileName = String.valueOf(System.currentTimeMillis());  
  282.                 Bitmap bm = (Bitmap) data.getExtras().get("data");  
  283.                 FileUtils.saveBitmap(bm, fileName);  
  284.                   
  285.                 ImageItem takePhoto = new ImageItem();  
  286.                 takePhoto.setBitmap(bm);  
  287.                 Bimp.tempSelectBitmap.add(takePhoto);  
  288.             }  
  289.             break;  
  290.         }  
  291.     }  
  292.       
  293.     public boolean onKeyDown(int keyCode, KeyEvent event) {  
  294.         if (keyCode == KeyEvent.KEYCODE_BACK) {  
  295.             for(int i=0;i<PublicWay.activityList.size();i++){  
  296.                 if (null != PublicWay.activityList.get(i)) {  
  297.                     PublicWay.activityList.get(i).finish();  
  298.                 }  
  299.             }  
  300.             System.exit(0);  
  301.         }  
  302.         return true;  
  303.     }  
  304.    
  305. }  
  306.    
  307.    

下載地址 : 微信上傳圖片源碼

備份下載地址:http://download.csdn.net/detail/jdsjlzx/8486449


補充:

通過GridView仿微信動態添加本地圖片

此篇文章主要講述GridView控件實現添加本地圖片並顯示.主要是關於GridView控件的基本操作,通常可以通過自定義繼承BaseAdapter的適配器加載圖片,而下面講述的不是自定義的適配器,而是調用SimpleAdapter實現的.至於上傳發布與網絡交互此處不講述,後面文章會講!

一. 實現效果

    主要是通過點擊+從本地相冊中添加圖片,同時顯示圖片至GridView.點擊圖片可以進行刪除操作,同時界面中的發佈EditView控件也很好看,不足之處在於+好沒有移動至最後,但原理相同.
      

二. 項目工程結構




三. 界面佈局詳細代碼

    1.主界面activity_main.xml
    主要通過相對佈局實現,第一部分是底部的TextView,中間是EditView和GridView相對佈局,下面是兩個按鈕.同時EditView調用res/drawable-hdpi中的editview_shape.xml,GridView顯示的每張圖片通過griditem_addpic.xml實現.

[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:id="@+id/container"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     tools:context="com.example.suishoupaipublish.MainActivity"  
  7.     tools:ignore="MergeRootFrame" >  
  8.       
  9.     <!-- 頂部添加文字 -->   
  10.     <RelativeLayout    
  11.         android:id="@+id/Layout_top"    
  12.         android:orientation="horizontal"     
  13.         android:layout_width="fill_parent"    
  14.         android:layout_height="40dp"    
  15.         android:layout_marginTop="5dp"  
  16.         android:layout_alignParentTop="true"    
  17.         android:gravity="center">    
  18.         <TextView    
  19.             android:layout_width="fill_parent"     
  20.             android:layout_height="wrap_content"      
  21.             android:textSize="25sp"  
  22.             android:gravity="center"  
  23.             android:text="發佈信息" />   
  24.     </RelativeLayout>    
  25.     <!-- 底部按鈕 -->    
  26.     <RelativeLayout    
  27.         android:id="@+id/Layout_bottom"     
  28.         android:layout_alignParentBottom="true"  
  29.         android:layout_width="fill_parent"     
  30.         android:layout_height="50dp"  
  31.         android:gravity="center" >    
  32.         <Button    
  33.             android:id="@+id/button1"    
  34.             android:layout_width="wrap_content"    
  35.             android:layout_height="fill_parent"  
  36.             android:textSize="20sp"  
  37.             android:text="發佈拍拍" />    
  38.         <Button    
  39.             android:id="@+id/button2"    
  40.             android:layout_width="wrap_content"    
  41.             android:layout_height="fill_parent"  
  42.             android:layout_toRightOf="@+id/button1"  
  43.             android:textSize="20sp"  
  44.             android:text="取消發佈" />  
  45.     </RelativeLayout>    
  46.     <!-- 顯示圖片 -->    
  47.     <RelativeLayout    
  48.         android:id="@+id/Content_Layout"       
  49.         android:layout_width="fill_parent"     
  50.         android:layout_height="fill_parent"    
  51.         android:layout_above="@id/Layout_bottom"     
  52.         android:layout_below="@id/Layout_top"      
  53.         android:gravity="center">       
  54.         <LinearLayout     
  55.             android:layout_width="match_parent"    
  56.             android:layout_height="match_parent"    
  57.             android:orientation="vertical"  
  58.             android:layout_alignParentBottom="true" >   
  59.             <!-- 設置運行多行 設置圓角圖形 黑色字體-->  
  60.             <EditText   
  61.                 android:id="@+id/editText1"  
  62.                 android:layout_height="120dp"  
  63.                 android:layout_width="fill_parent"  
  64.                 android:textColor="#000000"  
  65.                 android:layout_margin="12dp"  
  66.                 android:textSize="20sp"  
  67.                 android:hint="隨手說出你此刻的心聲..."  
  68.                 android:maxLength="500"  
  69.                 android:singleLine="false"  
  70.                 android:background="@drawable/editview_shape" />  
  71.             <!-- 網格顯示圖片 行列間距5dp 每列寬度90dp -->  
  72.             <GridView  
  73.                 android:id="@+id/gridView1"  
  74.                 android:layout_width="fill_parent"  
  75.                 android:layout_height="200dp"  
  76.                 android:layout_margin="10dp"  
  77.                 android:background="#EFDFDF"  
  78.                 android:horizontalSpacing="5dp"  
  79.                 android:verticalSpacing="5dp"  
  80.                 android:numColumns="4"  
  81.                 android:columnWidth="90dp"  
  82.                 android:stretchMode="columnWidth"  
  83.                 android:gravity="center" >  
  84.             </GridView>  
  85.             <TextView   
  86.                 android:layout_width="fill_parent"  
  87.                 android:layout_height="wrap_content"  
  88.                 android:text="(友情提示:只能添加9張圖片,長按圖片可以刪除已添加圖片)"  
  89.                 android:gravity="center" />  
  90.         </LinearLayout>  
  91.     </RelativeLayout>  
  92.       
  93. </RelativeLayout>  
    2.顯示ImageView圖片佈局griditem_addpic.xml
[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:gravity="center"  
  6.     android:descendantFocusability="blocksDescendants"  
  7.     android:orientation="vertical" >  
  8.     <RelativeLayout  
  9.         android:layout_gravity="center"  
  10.         android:layout_width="80dp"  
  11.         android:layout_height="80dp"  
  12.         android:orientation="vertical" >  
  13.         <ImageView  
  14.             android:layout_marginTop="10dp"  
  15.             android:layout_marginRight="10dp"  
  16.             android:id="@+id/imageView1"  
  17.             android:layout_width="fill_parent"  
  18.             android:layout_height="fill_parent"  
  19.             android:scaleType="fitXY"  
  20.             android:src="@drawable/gridview_addpic" />  
  21.     </RelativeLayout>  
  22. </LinearLayout>  
    3.設置EditView控件圓角和顏色 editview_shape.xml
[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"   
  3.     android:shape="rectangle"   
  4.     android:padding="10dp">  
  5.     <!-- 填充editView的顏色 -->  
  6.     <soild android:color="#ffffff"/>  
  7.     <!-- 設置圓角的弧度,radius半徑越大,editView的邊角越圓 -->  
  8.     <corners   
  9.         android:radius="15dp"  
  10.         android:bottomRightRadius="15dp"  
  11.         android:bottomLeftRadius="15dp"  
  12.         android:topLeftRadius="15dp"    
  13.         android:topRightRadius="15dp"/>  
  14.     <stroke  
  15.         android:color="#32CD32"    
  16.         android:width="4px" />   
  17. </shape>  

四. 代碼詳解


    它主要是思想如下:
    1.通過SimpleAdapter適配器實現實現加載圖片,在gridView1.setOnItemClickListener()點擊函數中響應不同操作.
    2.當點擊加號圖片(+)時,調用本地相冊通過Intent實現獲取圖片路徑存於字符串pathImage.
    3.獲取圖片路徑後在onResume中刷新圖片,通過GridView的setAdapter()和notifyDataSetChanged()()函數刷新加載圖片.
    4.點擊圖片時會獲取其position,通過dialog()函數彈出對話框提示是否刪除,通過remove實現刪除.

    具體代碼如下所示:
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public class MainActivity extends Activity {  
  2.   
  3.     private GridView gridView1;              //網格顯示縮略圖  
  4.     private Button buttonPublish;            //發佈按鈕  
  5.     private final int IMAGE_OPEN = 1;        //打開圖片標記  
  6.     private String pathImage;                //選擇圖片路徑  
  7.     private Bitmap bmp;                      //導入臨時圖片  
  8.     private ArrayList<HashMap<String, Object>> imageItem;  
  9.     private SimpleAdapter simpleAdapter;     //適配器  
  10.       
  11.     @Override  
  12.     protected void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.activity_main);  
  15.         /* 
  16.          * 防止鍵盤擋住輸入框 
  17.          * 不希望遮擋設置activity屬性 android:windowSoftInputMode="adjustPan" 
  18.          * 希望動態調整高度 android:windowSoftInputMode="adjustResize" 
  19.          */  
  20.         getWindow().setSoftInputMode(WindowManager.LayoutParams.  
  21.                 SOFT_INPUT_ADJUST_PAN);  
  22.         //鎖定屏幕  
  23.         setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  
  24.         setContentView(R.layout.activity_main);  
  25.         //獲取控件對象  
  26.         gridView1 = (GridView) findViewById(R.id.gridView1);  
  27.   
  28.         /* 
  29.          * 載入默認圖片添加圖片加號 
  30.          * 通過適配器實現 
  31.          * SimpleAdapter參數imageItem爲數據源 R.layout.griditem_addpic爲佈局 
  32.          */  
  33.         //獲取資源圖片加號  
  34.         bmp = BitmapFactory.decodeResource(getResources(), R.drawable.gridview_addpic);  
  35.         imageItem = new ArrayList<HashMap<String, Object>>();  
  36.         HashMap<String, Object> map = new HashMap<String, Object>();  
  37.         map.put("itemImage", bmp);  
  38.         imageItem.add(map);  
  39.         simpleAdapter = new SimpleAdapter(this,   
  40.                 imageItem, R.layout.griditem_addpic,   
  41.                 new String[] { "itemImage"}, new int[] { R.id.imageView1});   
  42.         /* 
  43.          * HashMap載入bmp圖片在GridView中不顯示,但是如果載入資源ID能顯示 如 
  44.          * map.put("itemImage", R.drawable.img); 
  45.          * 解決方法: 
  46.          *              1.自定義繼承BaseAdapter實現 
  47.          *              2.ViewBinder()接口實現 
  48.          *  參考 http://blog.csdn.net/admin_/article/details/7257901 
  49.          */  
  50.         simpleAdapter.setViewBinder(new ViewBinder() {    
  51.             @Override    
  52.             public boolean setViewValue(View view, Object data,    
  53.                     String textRepresentation) {    
  54.                 // TODO Auto-generated method stub    
  55.                 if(view instanceof ImageView && data instanceof Bitmap){    
  56.                     ImageView i = (ImageView)view;    
  57.                     i.setImageBitmap((Bitmap) data);    
  58.                     return true;    
  59.                 }    
  60.                 return false;    
  61.             }  
  62.         });    
  63.         gridView1.setAdapter(simpleAdapter);  
  64.           
  65.         /* 
  66.          * 監聽GridView點擊事件 
  67.          * 報錯:該函數必須抽象方法 故需要手動導入import android.view.View; 
  68.          */  
  69.         gridView1.setOnItemClickListener(new OnItemClickListener() {  
  70.             @Override  
  71.             public void onItemClick(AdapterView<?> parent, View v, int position, long id)  
  72.             {  
  73.                 if( imageItem.size() == 10) { //第一張爲默認圖片  
  74.                     Toast.makeText(MainActivity.this"圖片數9張已滿", Toast.LENGTH_SHORT).show();  
  75.                 }  
  76.                 else if(position == 0) { //點擊圖片位置爲+ 0對應0張圖片  
  77.                     Toast.makeText(MainActivity.this"添加圖片", Toast.LENGTH_SHORT).show();  
  78.                     //選擇圖片  
  79.                     Intent intent = new Intent(Intent.ACTION_PICK,         
  80.                             android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);    
  81.                     startActivityForResult(intent, IMAGE_OPEN);    
  82.                     //通過onResume()刷新數據  
  83.                 }  
  84.                 else {  
  85.                     dialog(position);  
  86.                     //Toast.makeText(MainActivity.this, "點擊第"+(position + 1)+" 號圖片",   
  87.                     //      Toast.LENGTH_SHORT).show();  
  88.                 }  
  89.             }  
  90.         });    
  91.     }  
  92.       
  93.     //獲取圖片路徑 響應startActivityForResult    
  94.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {    
  95.         super.onActivityResult(requestCode, resultCode, data);          
  96.         //打開圖片    
  97.         if(resultCode==RESULT_OK && requestCode==IMAGE_OPEN) {          
  98.             Uri uri = data.getData();    
  99.             if (!TextUtils.isEmpty(uri.getAuthority())) {    
  100.                 //查詢選擇圖片    
  101.                 Cursor cursor = getContentResolver().query(    
  102.                         uri,    
  103.                         new String[] { MediaStore.Images.Media.DATA },    
  104.                         null,     
  105.                         null,     
  106.                         null);    
  107.                 //返回 沒找到選擇圖片    
  108.                 if (null == cursor) {    
  109.                     return;    
  110.                 }    
  111.                 //光標移動至開頭 獲取圖片路徑    
  112.                 cursor.moveToFirst();    
  113.                 pathImage = cursor.getString(cursor    
  114.                         .getColumnIndex(MediaStore.Images.Media.DATA));    
  115.             }  
  116.         }  //end if 打開圖片  
  117.     }  
  118.       
  119.     //刷新圖片  
  120.     @Override  
  121.     protected void onResume() {  
  122.         super.onResume();  
  123.         if(!TextUtils.isEmpty(pathImage)){  
  124.             Bitmap addbmp=BitmapFactory.decodeFile(pathImage);  
  125.             HashMap<String, Object> map = new HashMap<String, Object>();  
  126.             map.put("itemImage", addbmp);  
  127.             imageItem.add(map);  
  128.             simpleAdapter = new SimpleAdapter(this,   
  129.                     imageItem, R.layout.griditem_addpic,   
  130.                     new String[] { "itemImage"}, new int[] { R.id.imageView1});   
  131.             simpleAdapter.setViewBinder(new ViewBinder() {    
  132.                 @Override    
  133.                 public boolean setViewValue(View view, Object data,    
  134.                         String textRepresentation) {    
  135.                     // TODO Auto-generated method stub    
  136.                     if(view instanceof ImageView && data instanceof Bitmap){    
  137.                         ImageView i = (ImageView)view;    
  138.                         i.setImageBitmap((Bitmap) data);    
  139.                         return true;    
  140.                     }    
  141.                     return false;    
  142.                 }  
  143.             });   
  144.             gridView1.setAdapter(simpleAdapter);  
  145.             simpleAdapter.notifyDataSetChanged();  
  146.             //刷新後釋放防止手機休眠後自動添加  
  147.             pathImage = null;  
  148.         }  
  149.     }  
  150.       
  151.     /* 
  152.      * Dialog對話框提示用戶刪除操作 
  153.      * position爲刪除圖片位置 
  154.      */  
  155.     protected void dialog(final int position) {  
  156.         AlertDialog.Builder builder = new Builder(MainActivity.this);  
  157.         builder.setMessage("確認移除已添加圖片嗎?");  
  158.         builder.setTitle("提示");  
  159.         builder.setPositiveButton("確認"new DialogInterface.OnClickListener() {  
  160.             @Override  
  161.             public void onClick(DialogInterface dialog, int which) {  
  162.                 dialog.dismiss();  
  163.                 imageItem.remove(position);  
  164.                 simpleAdapter.notifyDataSetChanged();  
  165.             }  
  166.         });  
  167.         builder.setNegativeButton("取消"new DialogInterface.OnClickListener() {  
  168.             @Override  
  169.             public void onClick(DialogInterface dialog, int which) {  
  170.                 dialog.dismiss();  
  171.                 }  
  172.             });  
  173.         builder.create().show();  
  174.     }  
  175.   
  176. }  
    同時需要在AndroidMainfest.xml中添加權限操作SD卡和網絡上傳至服務器.
[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <!-- 申明網絡權限  -->  
  2. <uses-permission android:name="android.permission.INTERNET" />  
  3. <!-- 申明權限 操作SD卡 -->    
  4. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  

五. 總結

    
    該文章需要注意一個地方:在使用SimpleAdapter適配器加載bmp圖片時,可能在GridView中不顯示.即HashMap中map.put("itemImage",bmp)不顯示圖片,而使用put裝入R.drawable.img卻能顯示.
    這時有兩種解決方法,一種是自定義繼承BaseAdapter的適配器實現;另一種方法則是如上所示通過ViewBinder()接口實現,感謝博主dmin_提供的方法.
    下載地址:http://download.csdn.net/detail/eastmount/8237429
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章