Implement ShareActionProvider for Android 4

In Android 4.0 (API Level 14), android.widget.ShareActionProvider is provided for share action. It is responsible for creating views that enable data sharing and also to show a sub menu with sharing activities if the hosting item is placed on the overflow menu.

It's a example to share plain text using ShareActionProvider.

Implement ShareActionProvider for Android 4

With share history:

With share history

Create /menu/menu.xml to define our ActionBar, with Share action only.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_item_share"
android:showAsAction="ifRoom"
android:title="Share"
android:actionProviderClass="android.widget.ShareActionProvider" />
</menu>


Main Java code:
package com.exercise.AndroidShareActionProvider;

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 AndroidShareActionProviderActivity extends Activity {

private ShareActionProvider myShareActionProvider;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.menu_item_share);
myShareActionProvider = (ShareActionProvider)item.getActionProvider();
myShareActionProvider.setShareHistoryFileName(
ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
myShareActionProvider.setShareIntent(createShareIntent());
return true;
}

private Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, 
"http://androidevsrom.blogspot.com/");
return shareIntent;
}

}


Download the files.

0 Response to "Implement ShareActionProvider for Android 4"

Post a Comment