Using ShareActionProvider with button in layout

I have a layout with a button. After clicking the button, I should be able to get the same functionality as the “Share button on the action bar” (which we can implement using ShareActionProvider). Tried to look for an example on the Internet; but could not find him. Is it possible?

+4
source share
1 answer

Yes, you can achieve the same functionality by firing an implicit intent in response to a button click. As below:

Main.java

public class MAIN extends Activity {


 @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


 }

 public void SHARE(View view) {

    // Do something in response to button

    EditText content = (EditText) findViewById(R.id.editText1);
     String shareBody = content.getText().toString();
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
            sharingIntent.setType("text/plain");
            sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "\n\n");
            sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
            startActivity(Intent.createChooser(sharingIntent,  getResources().getString(R.string.a5)));

 }
}

layout_main.java

<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"
tools:context="${relativePackage}.${activityClass}" >



            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="31dp"
                android:text="@string/MS1"
                android:gravity="center"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <EditText
                android:id="@+id/editText1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/textView1"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="36dp"
                android:ems="10" >

                <requestFocus />
            </EditText>

            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/editText1"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="50dp"
                android:onClick="SHARE"
                android:text="SEND" />

</RelativeLayout>

Hope this helps.

+4
source

All Articles