Advertisement

Pick image from gallery

 Pick an Image from gallery and show in image view :-



ActivityMain.xml :-


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageview"
android:layout_width="150dp"
android:layout_height="150dp"
android:background="@color/colorPrimaryDark"
android:layout_marginTop="200dp"
android:layout_marginLeft="140dp"
/>
</LinearLayout>


MainActivity.java :-



package com.example.pick;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView imgpick;
private static final int Gallery_REQUEST_CODE =1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgpick = findViewById(R.id.imageview);
imgpick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Pick an Image"),Gallery_REQUEST_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Gallery_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
Uri imagedata = data.getData();
imgpick.setImageURI(imagedata);
}
}
}


Post a Comment

0 Comments