Full tutorial is given below. Dear Viewer we are working hard to maintain this website. We doesn't want any think from you. Its just a humble request If you thinks that this posts helps you please share this post with your friends.
Share Image on button click - Android Studio
activity_main.xml
<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" > <ImageView android: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.usmtip.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.view.View; import android.widget.Button; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import java.io.File; import java.io.FileOutputStream; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //get image as bitmap from ImageView ImageView 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() { @Override public void onClick(View view) { //share image try { File file = new File(getExternalCacheDir(),"usmtipandroid.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 Comments: