Android image upload to achieve preview effect _android

Source: Internet
Author: User

First, the specific analysis, the implementation of the function, which needs analysis is essential, demand, logic cleared, then on the handwriting code, the idea will be very clear.

1. Multi-image upload first have to choose pictures (here The project needs are both can be photographed upload can also be selected from the album)

2. Photo upload is very simple. There are also many examples on the web, calling the camera, returning the URI, getting the picture

3. Select pictures from the album

    • 3.1 Get all the pictures in the phone
    • 3.2 Display the picture in the custom picture array
    • 3.3 Custom Viewpager Browse pictures

The main logic is generally this, the following specific look at the implementation:

First, look at the interface:

<com.view.noscrollgridview 
          android:id= "@+id/noscrollgridview" 
          android:layout_marginleft= "@dimen Smaller_space " 
          android:layout_marginright=" @dimen/smaller_space " 
          android:layout_width=" Match_parent " 
          android:layout_height= "wrap_content" 
          android:horizontalspacing= "3DP" 
          android:listselector= "@color /transparent " 
          android:numcolumns=" 3 " 
          android:scrollbars=" None " 
          android:layout_gravity=" center " 
          android:layout_margintop= "@dimen/smaller_space" 
          android:verticalspacing= "5DP"/> 

is a noscrollgridview, the project needs, so using the not rolling GridView, we use the GridView is the same.

Noscrollgridview = (GridView) Findviewbyid (R.id.noscrollgridview); 
    Noscrollgridview.setselector (New colordrawable (color.transparent)); 
    /* Create new Pass value to adapter*/ 
    if (file = = null) { 
      picadapter = new Pictureadapter (this, 0, null); 
    } else { 
      //Add failed pictures to number Group for 
      (int i=0;i<file.getmulfailfilepaths (). length;i++) { 
        Imageitem imageitem = new Imageitem (); 
        Imageitem.setimagepath (File.getmulfailfilepaths () [I].trim ()); 
        Bimp.tempSelectBitmap.add (Imageitem); 
      } 
      /* Upload failure pass value to adapter*/ 
      picadapter = new Pictureadapter (this, 2, file); 
    

This is the initialization of the image array, adapter (new, upload failed, upload successful pictures I used a adapter)

Imageitem is the model of the picture, which has its properties below

Pictures selected from the gallery model public class Imageitem extends File implements Serializable {@Id public String imageID;//Picture Id  
  Public String Thumbnailpath; Public String ImagePath;  
  Picture path private Bitmap Bitmap; 
   
  public Boolean isselected = false; 
  Public String Getimageid () {return imageid; 
  } public void Setimageid (String imageid) {This.imageid = imageID; 
  Public String Getthumbnailpath () {return thumbnailpath; 
  } public void Setthumbnailpath (String thumbnailpath) {this.thumbnailpath = Thumbnailpath; 
  Public String Getimagepath () {return imagepath; 
  } public void setImagePath (String imagepath) {this.imagepath = ImagePath; 
  public boolean isselected () {return isselected; 
  } public void SetSelected (Boolean isselected) {this.isselected = isselected;
} [Java] View plain copy print? /* bitmap*/public Bitmap Getbitmap () {if (Bitmap = = null) {try {Bitmap =) to get picture from picture path Bimp.revitionimagesize (ImagePath); 
    catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
} return bitmap; 
public void SetBitmap (Bitmap Bitmap) {this.bitmap = Bitmap;  }

Next is the adapter:

Because it involves adding a picture, adapter adds a flag to display the new picture, adds the selected picture to the public image array, and loads the image array display when initialized. (People can ignore my flag when they look at it.)

@SuppressLint ("Handlerleak") public class Pictureadapter extends Baseadapter {private Layoutinflater inflater; 
  private int selectedposition =-1; 
  Private Boolean shape; 
  private int flag = 0;//0 Default new 1 Upload success 2 upload failed private Appitem_file file; 
  public Boolean Isshape () {return shape; 
 
  Private activity context; 
  public void Setshape (Boolean shape) {this.shape = shape; 
    Pictureadapter (activity context,int flag,appitem_file file) {This.context = context; 
    Inflater = Layoutinflater.from (context); 
    This.flag = Flag; 
  This.file = file; 
}//public void Update () {//loading (); public int GetCount () {if (flag==0) {//new picture if (Bimp.tempSelectBitmap.size () = 6) {RET 
      Urn 6; 
    Return (Bimp.tempSelectBitmap.size () + 1); 
    else if (flag==1) {//Upload success return File.getfilelist (). Size (); else {//upload failed return file.getmulfailfilepaths (). lengtH 
    } public Object getitem (int arg0) {if (flag==1) {return file.getfilelist (). get (ARG0); 
    }else {return file.getmulfailfilepaths () [arg0]; 
  } public long Getitemid (int arg0) {return arg0; 
  The public void setselectedposition (int position) {selectedposition = position; 
  public int getselectedposition () {return selectedposition; 
    Public View GetView (int position, View Convertview, ViewGroup parent) {Viewholder holder = null; if (Convertview = null) {//load different layouts according to the number of pictures if (GetCount () ==1&&flag!=0) {Convertview = Infla 
      Ter.inflate (R.layout.item_published_singal_item, parent, false); 
      else {Convertview = Inflater.inflate (R.layout.item_published_grida, parent, false); 
      } holder = new Viewholder (); Holder.image = (ImageView) convertview. Findviewbyid (R.id.item_grida_image); 
      Convertview.settag (holder); 
    else {holder = (Viewholder) convertview.gettag ();  
     /** * According to the initialization of the adapter passed over the flag value, go to different places to find pictures * flag=0, to bimp image array to find * flag=1, proof upload successful, to download a good getfilelist to find * flag=2, for upload failed, picture saved in Failfile list<imageitem> * Optimized picture Display */if (flag==0) {//new picture if (Position = = Bimp.tempSelectBitmap.size ()) {Holder.image.setImageBitmap (Bitmapfactory.decoderesource) (Convertview.getresources (), r.drawable.i 
        con_add_pic_unfocused)); 
          if (position = = 6) {if (flag==0) {holder.image.setVisibility (view.gone); 
      }} else {Holder.image.setImageBitmap (Bimp.tempSelectBitmap.get (position). Getbitmap ()); 
} else if (flag==1) {//upload succeeded//list<integer> ids = new arraylist<integer> (); for (int i=0;i<file.getfilelist (). Size (); i++) {//Ids.add (File.getfilelist (). get (i). gets_id ()); 
      the int id=file.getfilelist (). get (position). gets_id (); 
        try {//File file= NeedApplication.db.findById (file.class,id); 
        String Filebigimguri =needapplication.db.findbyid (file.class,id). Getfileuribig (); if (filebigimguri!=null&&! " 
      Null ". Equals (Filebigimguri)) imageloader.getinstance (). DisplayImage ((Filebigimguri). Trim (), holder.image); 
      catch (Dbexception e) {e.printstacktrace (); 
        } else {//upload failed String url = "file://" +file.getmulfailfilepaths () [Position].trim (); 
    Imageloader.getinstance (). DisplayImage (URL, holder.image); 
  return convertview; 
  public class Viewholder {public ImageView image;  } 
 
}

  Below is a custom photo album interface to select a picture's

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "match_parent "Android:layout_height=" match_parent "android:background=" #E1E0DE "> <relativelayout android:id = "@+id/headview" android:layout_width= "fill_parent" android:layout_height= "45DP" android:background= "@drawa 
    Ble/plugin_camera_title_bar "android:gravity=" center_vertical "android:layout_marginbottom=" 3DP "> 
      <button android:layout_width= "60DP" android:layout_height= "wrap_content" android:textsize= "14SP" Android:textcolor= "#fff" android:id= "@+id/back" android:text= "album" Android:background= "@drawable /plugin_camera_title_btn_back "android:layout_margintop=" 5DP "android:layout_marginbottom=" 5DP "Andro Id:layout_centervertical= "true"/> <button android:layout_width= "67DP" Android:layout_hei ght= "Wrap_content" AndrOid:textsize= "14SP" android:textcolor= "#fff" android:id= "@+id/cancel" android:text= "Cancel" Androi d:background= "@drawable/plugin_camera_title_btn_cancel" android:layout_centervertical= "true" Android:layout_ marginright= "5DP" android:layout_alignparentright= "true"/> </RelativeLayout> <relative 
    Layout android:id= "@+id/bottom_layout" android:layout_width= "match_parent" android:layout_height= "50DP" Android:layout_alignparentbottom= "true" android:background= "@drawable/plugin_camera_bottom_bar" android:layout _margintop= "3DP" > <button android:id= "@+id/preview" android:layout_width= "90DP" Andr 
      oid:layout_height= "Wrap_content" android:layout_alignparentleft= "true" android:layout_centervertical= "true" android:layout_marginleft= "10DP" android:text= Preview "android:background=" @drawable/plugin_camera_title_ Btn_preview "/> <button android:id= "@+id/ok_button" android:layout_width= "90DP" android:layout_height= "Wrap_conten" T "android:layout_alignparentright=" true "android:layout_centervertical=" true "Android:layout_marginr 
 
  ight= "10DP" android:background= "@drawable/plugin_camera_ok_btn_state"/> </RelativeLayout> <gridview android:id= "@+id/mygrid" android:layout_width= fill_parent "android:layout_height=" fill_parent "Android:layout_above=" @id/bottom_layout "android:layout_below=" @id/headview "Android:layout_centerinparen T= "true" android:layout_margintop= "2DP" android:horizontalspacing= "10DP" android:numcolumns= "4" Androi d:verticalspacing= "10DP" android:background= "#E1E0DE"/> <textview android:id= "@+id/mytext" Androi D:layout_width= "Match_parent" android:layout_height= "match_parent" android:gravity= "center" android:text= "phase Album No picture "AndroId:textcolor= "@color/black"/> </RelativeLayout>  

Also used the GridView, get the picture in the phone, add to the array, show

Here used a Albumhelper (album Help Class), the Internet to find the code, feeling very good

Public list<imagebucket> getimagesbucketlist (Boolean refresh) { 
    if (Refresh | | (!refresh &&!hasbuildimagesbucketlist)) { 
      buildimagesbucketlist (); 
    } 
    list<imagebucket> tmplist = new arraylist<imagebucket> (); 
    iterator<entry<string, imagebucket>> ITR = Bucketlist.entryset () 
        . iterator (); 
    while (Itr.hasnext ()) { 
      entry<string, imagebucket> Entry = (entry<string, imagebucket>) ITR 
          . Next ( ); 
      Tmplist.add (Entry.getvalue ()); 
    } 
    return tmplist; 
  

When you get to the data source, it shows, that is, the method used to get the image help class

Initialize, assign a value to some objects private void init () {helper = Albumhelper.gethelper (); 
     
    Helper.init (Getapplicationcontext ()); 
    ContentList = Helper.getimagesbucketlist (false); 
    DataList = new arraylist<imageitem> (); 
    for (int i = 0; I<contentlist.size (); i++) {Datalist.addall (Contentlist.get (i). ImageList); 
    back = (Button) Findviewbyid (r.id.back); 
    Cancel = (Button) Findviewbyid (r.id.cancel); 
    Cancel.setonclicklistener (New Cancellistener ()); 
    Back.setonclicklistener (New Backlistener ()); 
    Preview = (Button) Findviewbyid (R.id.preview); 
    Preview.setonclicklistener (New Previewlistener ()); 
    Intent = getintent (); 
    Bundle Bundle = Intent.getextras (); 
    GridView = (GridView) Findviewbyid (R.id.mygrid); 
    Gridimageadapter = new Albumgridviewadapter (MCONTEXT,DATALIST,BIMP.TEMPSELECTBITMAP); 
    Gridview.setadapter (Gridimageadapter); 
    TV = (TextView) Findviewbyid (R.id.mytext); 
 Gridview.setemptyview (TV);   OKButton = (Button) Findviewbyid (R.id.ok_button); 
  Okbutton.settext ("Complete" + "(" + Bimp.tempSelectBitmap.size () + "/" + needapplication.picnums+ ")"); 

 }
Gridimageadapter. Setonitemclicklistener (New Albumgridviewadapter.onitemclicklistener () {@Override  public void Onitemclick (final ToggleButton ToggleButton, int position, Boolean Ischecked,button CHOOSEBT) {if (Bimp.tempSelectBitmap.size () >= needapplication.picnums) {togglebutton.se 
              Tchecked (FALSE); 
              Choosebt.setvisibility (View.gone); if (!removeonedata (datalist.get (position))) {Toast.maketext (Albumactivity.this, "exceeds the number of optional pictures", toast.length 
              _short). Show (); 
            } return; 
              } if (ischecked) {choosebt.setvisibility (view.visible); 
              Bimp.tempSelectBitmap.add (Datalist.get (position)); 
            Okbutton.settext ("Complete" + "(" + Bimp.tempSelectBitmap.size () + "/" + needapplication.picnums+ ")"); else {Bimp.tempSelectBitmap.remove (Datalist.get (POSition)); 
              Choosebt.setvisibility (View.gone); 
            Okbutton.settext ("Complete" + "(" + Bimp.tempSelectBitmap.size () + "/" + needapplication.picnums+ ")"); 
          } ISSHOWOKBT (); 
 } 
        });

Click on the image selected to add to the public image array to display the selected.

The last is to preview the picture, using the custom Viewpager, to achieve the picture slide, the following two screenshots:

The above is the entire content of this article, I hope to help you learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.