Search This Blog

Monday, 26 August 2013

ShareActionProvider implementation in android newest version

Action Bar comes under standard design pattern of Android. ShareActionProvider is another easy step to implement Action Bar if we need to share some Intent with other application installed in the device.
ShareActionProvider introduce by android team in Android version 4.0 and above and this does not support any backward compatibility.
So lets create one simple demo of ShareActionProvider.

1) Update you menu file to create ShareActionProvider

 <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>  

2) Update your MainActivity to create ShareActionProvider

 public class MainActivity extends Activity {  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
      }  
      private ShareActionProvider mShareActionProvider;  
      @Override  
      public boolean onCreateOptionsMenu(Menu menu) {  
           // Inflate menu resource file.  
           getMenuInflater().inflate(R.menu.main, menu);  
           // Locate MenuItem with ShareActionProvider  
           MenuItem item = menu.findItem(R.id.menu_item_share);  
           // Fetch and store ShareActionProvider  
           mShareActionProvider = (ShareActionProvider) item.getActionProvider();  
           setShareIntent(createShareIntent());  
           // Return true to display menu  
           return true;  
      }  
      // Call to update the share intent  
      private void setShareIntent(Intent shareIntent) {  
           if (mShareActionProvider != null) {  
                mShareActionProvider.setShareIntent(shareIntent);  
           }  
      }  
      private Intent createShareIntent() {  
           Intent shareIntent = new Intent(Intent.ACTION_SEND);  
           shareIntent.setType("text/plain");  
           shareIntent.putExtra(Intent.EXTRA_TEXT,  
                     "http://androidtrainningcenter.blogspot.in");  
           return shareIntent;  
      }  
 }  

3) Let see how we create an intent to share with other application

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




Source

http://developer.android.com/training/sharing/shareaction.html

No comments:

Post a Comment

Feedback always help in improvement. If you have any query suggestion feel free to comment and Keep visiting my blog to encourage me to blogging

Android News and source code