Adding Share Button – Android Studio

Hello Android Lovers, In this article I am going to discuss how to add a share button. So lets start “Adding share button – Android Studio” article.

If you are a newbie to Android. Follow and refer articles.

Adding Share Button – Android Studio

First of all, we need to create a button in the layout file. So here is the code for that.

<Button
    android:id="@+id/btnShare"
    android:text= "Share"
    android:layout_width="match_parent"
    android:layout_height="50dp"/>

After you creating the layout file, then go the Java file.

In your Java file, first add properties.

private Button btnShare;
public static String PACKAGE_NAME;

We need the package name to implement the share option.

Then define in the onCreate() method.

btnShare= findViewById(R.id.btnShare);
PACKAGE_NAME = getApplicationContext().getPackageName();

We are going to develop share option when the button click. So we have to implement the setOnClickListener method.

#Step 02 setOnClickListener method

First of all, I am going to create another method to implement share option. I am calling that as ShareMe(). Here is the ShareMe() Code.

 private void ShareMe(String url){
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        String value = url + PACKAGE_NAME;
        intent.putExtra(Intent.EXTRA_TEXT, value);
        startActivity(Intent.createChooser(intent,"Share Via"));
 }

In here I am creating a Intent and pass the ACTION_SEND. Then create a variable to set the URL and the package name.

When you assign this ShareMe() method, you have to pass the URL that you are going to share. In here I am going to share my Plays tore app.

After that we are going to implement the setOnClickListener() method. Here is the code for that.

btnShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ShareMe("https://play.google.com/store/apps/details?id=");
            }
});

In here I am passing my URL that I want to share. That’s it.

Thank you