How to Share Image on button click - Android Studio
In this tutorial we will learn how to share the Image. We will get image from ImageView and share it by clicking a Button. When Button is clicked sharing intent will appear listing available apps that can share that Image.
Step 1: Create a new project OR Open your project
Step 2: Place an image in drawable folder
Step 3: Code
activity_main.xml
MainActivity.java
<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"android:padding="10dp"tools:context=".MainActivity" ><ImageViewandroid:id="@+id/imageView"android:textAlignment="center"android:src="@mipmap/ic_launcher_round"android:layout_gravity="center"android:layout_width="300dp"android:layout_height="300dp" /> <Button android:id="@+id/btnShare" android:text="Share Image" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout>
MainActivity.java
package com.blogspot.devofandroid.myapplication;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.drawable.BitmapDrawable;import android.graphics.drawable.Drawable;import android.net.Uri;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView;import java.io.File;import java.io.FileOutputStream;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//get image as bitmap from ImageViewImageView post_image = (ImageView)findViewById(R.id.imageView);Drawable myDrawable = post_image.getDrawable();final Bitmap bitmap = ((BitmapDrawable) myDrawable).getBitmap();Button mBtnShare = findViewById(R.id.btnShare);mBtnShare.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//share imagetry {File file = new File(getExternalCacheDir() ,"devofandroid.png");FileOutputStream fOut = new FileOutputStream(file);bitmap.compress(Bitmap.CompressFormat.PNG , 100 , fOut);fOut.flush();fOut.close();file.setReadable(true , false);final Intent intent = new Intent(android.content.Intent.ACTION_SEND);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.putExtra(Intent.EXTRA_STREAM , Uri.fromFile(file));intent.setType("image/png");startActivity(Intent.createChooser(intent , "Share image via"));} catch (Exception e) {e.printStackTrace();}}});}}
0 Response to "Share Image On Button Click - Android Studio"