How Android selects pictures from the System gallery

Source: Internet
Author: User

I've been doing Android apps these days, and I've been learning its API, and I'm going to share some of the things I've learned, such as: How to choose a picture from the system gallery.

First, let's take a look at how to integrate the phone system library into your app and then choose a picture from the gallery to do something. For example, on the Facebook app, you can directly select the images on your phone to upload to your profile.

Let's do a simple example that requires:

    1. A button and a picture view control appear on the screen.

    2. Click the "Load Picture" button to redirect the user to the Android picture library, where you can select a picture.

    3. Once the picture is selected, the picture is displayed in the Picture view control on the main screen.

Let's get started.

Step 1: Create a basic Android project

In Eclipse, click New > Project > AndroidProject, name the project "Imagegallerydemo", and then select Android2.1 or SDK 7.

Once this step is complete, you will see a basic Hello World program.

Step 2: Modify the Layout file

In our example, we need a simple layout: a ImageView control to display our selected picture, a button control click Redirect to the phone library.

Open Layout/main.xml in the project and replace it with the following code:

<?xml version= "1.0"  encoding= "Utf-8"? ><linearlayout xmlns:android= "http// Schemas.android.com/apk/res/android "    android:orientation=" vertical "     android:layout_width= "Fill_parent"     android:layout_height= "Fill_parent" >     <imageview        android:id= "@+id/imgView"          android:layout_width= "Fill_parent"          android:layout_height= "Wrap_content"         android: layout_weight= "1" ></ImageView>    <Button         android:id= "@+id/buttonloadpicture"         android:layout_ Width= "Wrap_content"         android:layout_height= "Wrap_content"          android:layout_weight= "0"         android:text= "Load  Picture "        android:layout_gravity=" center ></Button>< /linearlayout>


Now we need to write some Java code to handle the button's click events, and the code to redirect to the picture library is as follows: Step 3: Write the code redirected to the picture library

Intent i = new Intent (Intent.action_pick, Android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); Startactivityforresult (i, result_load_image);


Note : This is going to pass an integer constant. Result_load_image to thestartActivityForResult()方法。

Step 4: Get the selected picture

Once the user selects a picture, the Onactivityresult () method is called. We need to deal with this method to get the data, the code is as follows:

@Overrideprotected  void onactivityresult (int requestcode, int resultcode, intent  data)  {    super.onactivityresult (requestcode, resultcode, data);      if  (requestcode == result_load_image &&  Resultcode == result_ok && null != data)  {         uri selectedimage = data.getdata ();         String[] filePathColumn = { MediaStore.Images.Media.DATA };          cursor cursor = getcontentresolver (). Query ( selectedimage,                 Filepathcolumn, null, null, null);         Cursor.movetofirst ();     &nBsp;    int columnindex = cursor.getcolumnindex (filePathColumn[0]);         string picturepath = cursor.getstring (ColumnIndex);         cursor.close ();          // string picturepath contains the path of selected image}

Note : The Onactivityresult () method is called only if the picture is selected. In this method, we need to check if Requestcode is the result_load_image we passed to the Startactivityforresult () method before .

Final Code
ImageGalleryDemoActivity类的最终代码如下:

package net.viralpatel.android.imagegalleray;  import android.app.activity;import  Android.content.intent;import android.database.cursor;import android.graphics.bitmapfactory;import  android.net.Uri;import android.os.Bundle;import android.provider.MediaStore;import  Android.view.view;import android.widget.button;import android.widget.imageview;  public  class ImageGalleryDemoActivity extends Activity {       private static int result_load_image = 1;      @ Override    public void oncreate (bundle savedinstancestate)  {         super.oncreate (savedinstancestate);         setcontentview (R.layout.main);           Button buttonloadimage =  (Button)  findviewbyid (r.id.buttonloadpicture);         Buttonloadimage.setonclicklistener (New view.onclicklistener ()  {                @Override              public void onclick (view arg0)  {                   intent i = new  intent (                         Intent.ACTION_PICK,                          Android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);                    startactivityforresult (I, result_load_image);             }        });     }       @Override     protected void  Onactivityresult (Int requestcode, int resultcode, intent data)  {         super.onactivityresult (Requestcode, resultcode, data);           if  (requestcode == result_load_image  && resultcode == result_ok && null != data)  {             Uri selectedImage =  Data.getdata ();            string[]  Filepathcolumn = { mediastore.images.media.data };              cursor  Cursor = getcontentresolver (). Query (selectedimage,                     filepathcolumn, null, null,  null);             cursor.movetofirst ();               int columnIndex  = cursor.getcolumnindex (filepathcolumn[0]);             string picturepath = cursor.getstring (columnindex);             cursor.close ();               ImageView imageView =  (ImageView)  findviewbyid ( R.id.imgview);    &nBsp;        imageview.setimagebitmap (BitmapFactory.decodeFile ( PicturePath));          }       }}

Program

First screen: Users will be redirected to the phone gallery

User selects pictures from gallery

Display user-selected pictures in our app

Source code: Imagegallerydemo.zip (KB)


How Android selects pictures from the System gallery

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.