Friday, July 25, 2014

Adding an Easy Share Action in Android App

MainActivity.java

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 {
private ShareActionProvider mShareActionProvider;
Intent mShareIntent;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mShareIntent = new Intent();
mShareIntent.setAction(Intent.ACTION_SEND);
mShareIntent.setType("text/plain");
mShareIntent.putExtra(Intent.EXTRA_TEXT,
"From me to you, this text is new.");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.more_tab_menu, menu);

// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);

// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(mShareIntent);
}
// Return true to display menu
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return super.onOptionsItemSelected(item);
}

}

more_tab_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_item_share"
        android:actionProviderClass="android.widget.ShareActionProvider"
        android:showAsAction="ifRoom"
        android:title="Share"/>

</menu>