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.
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.
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.
You can use any medium like Facebook, WhatsApp, email, messaging, Bluetooth, etc. to share your message.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.