How to create simple android Share button
Today we are going to learn how to create a simple android share button.
Lessons to learn:
- Adding Toolbar
- Using WebView
- Creating android menu
- Using onOptionsItemSelected method to listen to selected MenuItems.
Let get started
Create a new project and name it "EasyShareExample"
Package name :net.techoverload.www.easyshareexample
Add some drawables i.e Notification,settings and share
activity_main.xml code
MainActivity.java code
package net.techoverload.www.easyshareexample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar=findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
webView=findViewById(R.id.webView);
WebSettings webSettings=webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("http://www.mafisizone.com");
}
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.top_nav,menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.top_nav_share:
{
String tittle=webView.getTitle();
String url=webView.getUrl();
//sharing implementation here
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, tittle);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, url);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
return true;
}
}
return true;
}
}
Menu.xml code
Output

