In your application, you might want to allow the user to pick an image from the gallery for later processing. In this Android, I am going to show you how to achieve this goal using Intent and onActivityResult() method.
First you have to create an Intent object for PICK action. You also specify the URI of the gallery in which an image will be picked from. Typically this URI is MediaStore.Images.Media.EXTERNAL_CONTENT_URI. Then you call the startActivityForResult() method to launch the gallery application. You pass the intent object and request code to the startActivityForResult() method. The question code will be returned in the onActivityResult() method. So you can determine whether the gallery returns what you have requested. The onActivityResult() has a Intent parameter that stores the URI of the image. In the example code below, the URI of the picked image is passed to the setImageURI() method of an ImageView object to display.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.inputdialog.MainActivity" >
<ImageView
android:id="@+id/imgview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class MainActivity extends Activity{
private final int REQUEST_CODE=10;
ImageView iv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv=(ImageView)findViewById(R.id.imgview);
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode ==REQUEST_CODE && data != null && data.getData() != null) {
Uri uri = data.getData();
iv.setImageURI(uri);
}
}
}
|
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.