Home » Android » ShareActionProvider without any action bar in android

ShareActionProvider without any action bar in android

Posted by: admin June 15, 2020 Leave a comment

Questions:

I do not want an action bar in my app and still want to have that share button that is provided by the action bar.

This is done when action bar is there.

public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);
    ShareActionProvider provider = (ShareActionProvider)
    menu.findItem(R.id.menu_share).getActionProvider();

    if (provider != null) {
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_TEXT, "hi");
        shareIntent.setType("text/plain");
        provider.setShareIntent(shareIntent);
    }

    return true;
}

And the menu.xml is kept in menu folder.

Where as I want a share button of my own in my xml where other layouts are also defined.

any help?

How to&Answers:

You don’t need an Action Bar to share content. In fact, even with an Action Bar, most apps don’t use the ShareActionProvider because visually designers hate it and it doesn’t support a lot of the latest share features on a users device (like direct sharing to contacts). Instead you should use Intent.createChooser to create a more robust share dialog.

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));

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

An even better way to Share from anywhere in your app is to use ShareCompat. Here is a quick example:

ShareCompat.IntentBuilder.from(this)
           .setType("text/plain")
           .setText("I'm sharing!")
           .startChooser();

Other examples can be found here: https://android.googlesource.com/platform/development/+/master/samples/Support4Demos/src/com/example/android/supportv4/app/SharingSupport.java

Answer:

Use PackageManager and queryIntentActivities() to find the apps that know how to handle the ACTION_SEND Intent that you want to invoke. Display the resulting list however you would like. When the user makes a selection, create a equivalent ACTION_SEND Intent, where you specify the ComponentName of the particular activity that the user chose, and call startActivity().

Answer:

Use an Intent with ACTION_SEND. For example, when a button is clicked you could:

Intent It = new Intent(Intent.ACTION_SEND);
It.setType("text/plain");
It.putExtra(android.content.Intent.EXTRA_TEXT,"your_text_to_share");
YourActivity.this.startActivity(It);