Android allows to re-use components from other applications. Lets see how you can use the Photo Gallery to pick a photo for your application.
First create a layout with a Button and an ImageView.
<?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">
<Button android:text="Button" android:id="@+id/button1"
android:onClick="pickImage" android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
<ImageView android:id="@+id/result" android:src="@drawable/icon"
android:layout_width="match_parent" android:layout_height="match_parent"></ImageView>
</LinearLayout>
The following Activity will allow you to pick an image after pressing the button and after selecting a picture this picture will be set as background for your ImageView.
package de.vogella.android.imagepick;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class ImagePickActivity extends Activity {
private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
private ImageView imageView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.result);
}
public void pickImage(View View) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
// We need to recyle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}
InputStream stream = getContentResolver().openInputStream(
data.getData());
bitmap = BitmapFactory.decodeStream(stream);
stream.close();
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Updated: recycle() call to bitmap added
I hope this blog entry helps. You find me also on Twitter. My profile can be found Dharma Kshetri Profile
.
0 comments
Thanks for your comment