Introduction
In this article, we are going to see how to create a share button in the Android app using Android Studio. It is used to share the social links to any other sources in our mobile. This link can be provided by us.
Step 1
Create a new project in Android Studio.
Give a name to the project and click "Next".
Select the "Phone and Tablet" and click "Next".
Select an empty activity and click "Next".
At last, give the activity name and click on "Finish".
Step 2
Set up the Gradle by just locating the Gradle Scripts>>Build.Gradle
And type the following dependency in your app's build.gradle.
Code copy is here,
- maven
- {
- url "https://jitpack.io"
- }
Step 3
Next, go to app >> res >> layout >> activity_main.xml. Select activity page
And just type the code as follows.
Code copy is here
- <Button
- android:id="@+id/button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Share It"
- tools:layout_editor_absoluteX="141dp"
- tools:layout_editor_absoluteY="231dp"
- />
Step 4
Next, go to app >> java>>Mainactivity.java. Select Mainactivity page,
And just type the code as follows,
Code copy is here
- Button button;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- button = (Button) findViewById(R.id.button);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- Intent myIntent = new Intent(Intent.ACTION_SEND);
- myIntent.setType("text/plain");
- String shareBody = "Your body is here";
- String shareSub = "Your subject";
- myIntent.putExtra(Intent.EXTRA_SUBJECT, shareBody);
- myIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
- startActivity(Intent.createChooser(myIntent, "Share using"));
- }
- });
Note
You have to provide your link in the 13th line inside sharebody.
Step 5
After step 4, Sync all the dependency gradles and Mainactivity.java resource files by clicking the Sync button on the top right corner of the Gradle page.
Step 6
Verify the preview.
->After the code is applied, the preview will appear like this.
Step 7
Next, go to Android Studio and deploy the application. Select an Emulator or your Android mobile with USB debugging enabled. Give it a few seconds to make installations and set permissions.
Run the application in your desired emulator (Shift + F10).
Explanation of source code
The source code provided in this article is just the dependencies of share option and the code used in activity_main.xml will make the button sharable and define its attributes.
Summary
In this article we created the app named Share Data, then we have inserted a Gradle and we learned how to give a share option to the button and finally, we have deployed that as an output.
*Support and Share, Thank You*