how to add Share Action in android

0 589

Share Action in android

in this tut I will teach you how you can add share action to title bar,you can add share action anywhere in an app but in this tut, I will show you to add in title bar.when user click the share on title bar there will be many options to share your content behalf on user chosen apps

How to Add Share Action to title bar

Main activity.java

In main activity in onCreateOptionsMenu method, we will define our codes

package com.example.exceptionbound;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;

public class MainActivity extends Activity {

	@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);
		MenuItem menushareitem = (MenuItem) menu.findItem(R.id.action_share);
		ShareActionProvider shareactionprovider = (ShareActionProvider) menushareitem.getActionProvider();

		Intent shareIntent = new Intent(Intent.ACTION_SEND);
		shareIntent.setAction(Intent.ACTION_SEND);
		shareIntent.setType("text/plain");
		shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello jimmy");
		shareactionprovider.setShareIntent(shareIntent);

		return super.onCreateOptionsMenu(menu);
	}
}

Activit_mian.xml

In layout, we have simple Relative layout with one text view

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

Main.xml

For menu in main.xml we have defines id , showAsAction, actionProviderClass, and orderInCategory

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

   <item android:id="@+id/action_share"
       android:showAsAction="ifRoom"
       android:actionProviderClass="android.widget.ShareActionProvider"
       android:orderInCategory="100"
       />

</menu>

Download Share Action source code

 

Comments

comments

Leave A Reply

Your email address will not be published.