Wednesday, 18 February 2015

Adding a Share Button to Your Android Apps

Code:

<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">
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="title"
    android:id="@+id/btnNext"/>

</RelativeLayout>

MainActivity:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

private Button btn;

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

   setContentView(R.layout.activity_main);
   btn = (Button)findViewById(R.id.btnNext);
   btn.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
       
        //create the send intent
        Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
       
        //set the type
        shareIntent.setType("text/plain");
       
        //add a subject
        shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,  
        "Insert Subject Here");
       
        //build the body of the message to be shared
        String shareMessage = "Insert message body here.";
       
        //add the message
        shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,  
        shareMessage);
       
        //start the chooser for sharing
        startActivity(Intent.createChooser(shareIntent,  
        "Insert share chooser title here"));  
       
       }
   });    
}

}




No comments:

Post a Comment