Wednesday, February 16, 2011

Select Image using Android build-in Gallery

If you have to select image from SD in your app, and don't want to implement a file browser by yourself; you can call the Android build-in Gallery to do so, using Intent.

Select Image using Android build-in Gallery

Here is a example:
package com.exercise.AndroidSelectImage;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AndroidSelectImage extends Activity {

TextView textTargetUri;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      Button buttonLoadImage = (Button)findViewById(R.id.loadimage);
      textTargetUri = (TextView)findViewById(R.id.targeturi);
    
      buttonLoadImage.setOnClickListener(new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   Intent intent = new Intent(Intent.ACTION_PICK,
     android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
   startActivityForResult(intent, 0);
  }});
  }

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 // TODO Auto-generated method stub
 super.onActivityResult(requestCode, resultCode, data);

 if (resultCode == RESULT_OK){
  Uri targetUri = data.getData();
  textTargetUri.setText(targetUri.toString());
 }
}
}


<?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"
  >
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello"
  />
<Button
  android:id="@+id/loadimage"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Load Image"
  />
<TextView
  android:id="@+id/targeturi"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
</LinearLayout>


download filesDownload the files.

next:
- Display Gallery selected image using BitmapFactory

related:
- Send email with Image by starting activity using Intent of ACTION_SEND
Convert Uri return from Gallery to file path
- Convert between Uri and file path, and load Bitmap from.

No comments:

Post a Comment