Latest News

Share Image On Button Click (Kotlin) - 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 3: Place an image in res>drawable folder

Step 3: Code

activity_main.xml
<?xml version="1.0" encoding="utf-8"?><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" /><Buttonandroid:id="@+id/btnShare"android:text="Share Image"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>


MainActivity.kt
package com.blogspot.devofandroid.myapplicationimport android.content.Intentimport android.graphics.Bitmapimport android.graphics.drawable.BitmapDrawableimport android.net.Uriimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport android.widget.ImageViewimport java.io.Fileimport java.io.FileOutputStreamimport java.lang.Exceptionclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)//get image as bitmap from ImageViewval post_image = findViewById<View>(R.id.imageView) as ImageViewval myDrawable = post_image.drawableval bitmap = (myDrawable as BitmapDrawable).bitmapval mBtnShare = findViewById<Button>(R.id.btnShare)mBtnShare.setOnClickListener {//share imagetry {val file = File(externalCacheDir , "devofandroid.png")val fOut = FileOutputStream(file)bitmap.compress(Bitmap.CompressFormat.PNG , 100 , fOut)fOut.flush()fOut.close()file.setReadable(true , false)val intent = Intent(android.content.Intent.ACTION_SEND)intent.flags = Intent.FLAG_ACTIVITY_NEW_TASKintent.putExtra(Intent.EXTRA_STREAM , Uri.fromFile(file))intent.type = "image/png"startActivity(Intent.createChooser(intent , "Share image via"))} catch (e: Exception) {e.printStackTrace()}}}}

Step 4: Output

Share Image on button click (Kotlin)
Share Image on button click (Kotlin)
Share Image on button click (Kotlin)
Share Image on button click (Kotlin)


0 Response to "Share Image On Button Click (Kotlin) - Android Studio"