Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to add Custom Spinner in Android?
Next article icon

How to Add Share Button in Toolbar in Android?

Last Updated : 09 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to create a simple Share Button in the Toolbar in Android. The Share Button is used to share information on mail, Bluetooth, Facebook, Twitter, WhatsApp, etc to an individual person or a group on any social media. We can share any type of message like text, images, videos, links, etc. Note that we are using Java as the programming language. A sample video is given below to get an idea about what we are going to do in this project. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Create a New Android Resource Directory

Go to the res folder, right-click on it and follow the steps shown in the below image to create a new Android Resource Directory. 

Now Right-click on Android Resource Directory, a new tab is opened. Do as shown below:

Give a name to your directory and click ok. A new Android Resource Directory is created. 

Step 3: Create a Menu Resource File

Go to the menu directory, right-click on it and follow the images given below:

Now right-click on Menu Resource Directory and do as shown in the image below:

Give a name to your file and then click ok. A new Menu Resource File has been created.

Step 4: Create an icon

Navigate to res > drawable. Now, right-click on the drawable folder and follow the images given below:

Now right-click on Vector Asset and do as shown below:

i) choose the icon by clicking on clip-art and then search for icon share. 

if you want to give some to your icon then write it in Name, otherwise, the default name is generated.

ii) choose a color for your icon by clicking on the color option 

Click on choose then next and finish, your icon has been created. Here ic_baseline_share_24 is given by default.

Step 5: Working with the main_menu.xml

Navigate to res > menu > main_menu.xml and add the below code to that file. 

XML
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"       xmlns:app="http://schemas.android.com/apk/res-auto">      <!--we are using  app:showAsAction="ifRoom" so that share         button is added in toolbar. -->     <item         android:id="@+id/shareButton"         android:icon="@drawable/ic_baseline_share_24"         android:title="SHARE"         app:showAsAction="ifRoom" />  </menu> 

Step 6: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout      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"     tools:context=".MainActivity">      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Hello GFG !!"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintLeft_toLeftOf="parent"         app:layout_constraintRight_toRightOf="parent"         app:layout_constraintTop_toTopOf="parent" />  </androidx.constraintlayout.widget.ConstraintLayout> 

Step 7: Working with the MainActivity.java file

Go to the MainActivity.java file and add the code given below. We have implemented two methods public boolean onCreateOptionsMenu() and public boolean onOptionsItemSelected() here. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java
import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem;  import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity;  public class MainActivity extends AppCompatActivity {      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);     }      @Override     public boolean onCreateOptionsMenu(Menu menu) {          getMenuInflater().inflate(R.menu.main_menu, menu);                  // first parameter is the file for icon and second one is menu            return super.onCreateOptionsMenu(menu);     }      @Override     public boolean onOptionsItemSelected(@NonNull MenuItem item) {         // We are using switch case because multiple icons can be kept         switch (item.getItemId()) {             case R.id.shareButton:                                  Intent sharingIntent = new Intent(Intent.ACTION_SEND);                                  // type of the content to be shared                 sharingIntent.setType("text/plain");                                  // Body of the content                 String shareBody = "Your Body Here";                                  // subject of the content. you can share anything                 String shareSubject = "Your Subject Here";                                  // passing body of the content                  sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);                                  // passing subject of the content                 sharingIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubject);                 startActivity(Intent.createChooser(sharingIntent, "Share using"));                 break;         }         return super.onOptionsItemSelected(item);     } } 

Output:

You can use any medium like Facebook, WhatsApp, email, messaging, Bluetooth, etc. to share your message.


Next Article
How to add Custom Spinner in Android?

A

annulata2402
Improve
Article Tags :
  • Java
  • Android
Practice Tags :
  • Java

Similar Reads

  • How to Add Custom Toolbar Background in Android?
    A toolbar is basically a form action bar that contains many interactive items. A toolbar supports a more focused feature than an action bar. The toolbar was added in Android Lollipop (API 21) and is the successor of the ActionBar. The toolbar is a ViewGroup that can be put anyplace in the XML layout
    3 min read
  • How to add Custom Spinner in Android?
    Spinner is a widget that is used to select an item from a list of items. When the user tap on a spinner a drop-down menu is visible to the user. In this article, we will learn how to add custom spinner in the app. Steps of Implementing Custom SpinnerStep 1: Create a new layout for each item in Spinn
    5 min read
  • How to Create Buttons Inside a Widget in Android?
    PrerequisitesHow to Create a Basic Widget of an Android App?How to Create a Dynamic Widget of an Android App?A Widget is a mini version of an Application, that provides a ground for the user to navigate through it or use its features from the Home Screen or Lock Screen. Widgets contain elements acco
    4 min read
  • How to change Input Method Action Button in Android?
    In this article, IME(Input Method Action) Option is changed in android according to our requirement. Input Method Action Button is located in the bottom right corner of the soft keyboard. By default, the system uses this button for either a Next or Done action unless your text field allows multi-lin
    2 min read
  • How to Add YouTube Live Stream Feature in Android?
    YouTube provides a service to make a live stream video on their platform to connect with your subscribers. In this article, we will take a look at the implementation of YouTube video live streaming video in Android App.  What we are going to build in this article?  We will be building a simple appli
    4 min read
  • How to Customize Option Menu of Toolbar in Android?
    In this article, we will see how to add icons and change background color in the options menu of the toolbar. Option menu is a collection of menu items of an activity. Android Option Menus are the primary menus of the activity. They can be used for settings, search, delete items, etc. We will first
    3 min read
  • How to Collapse Toolbar Layout in Android?
    In this article, we are going to create the CollapsingToolbar app that is fascinating and much useful. CollapsingToolbarLayout gives the facility of adjusting the size of toolbar title text when it is expanded or contracted. A sample GIF is given below to get an idea about how CollapsingToolbarLayou
    4 min read
  • How to Add Image on EditText in Android?
    In Android, An EditText is an overlay over a TextView that makes it editable using text by invoking a soft keyboard in run time. It is generally implemented to collect text data from the user. EditText is most commonly used in forms that require users to fill in details and for passing a search quer
    3 min read
  • Double-Tap on a Button in Android
    Detecting a Double Tap on Button in Android i.e. whenever the user double taps on any Button how it is detected and according to the Button a response can be added corresponding to it. Here an example is shown in which the double tap on the Button is detected and the corresponding to it response is
    3 min read
  • How to Add Image on Floating Action Button in Android?
    A floating action button (FAB) is a user interface element in the mobile application that is typically circular and floats above the main content. It usually has a prominent color and icon, and it is used to provide quick access to the most commonly used action within the app. Step-by-Step Implement
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences