Share text of TextView on button click (Kotlin) - Android Studio

In this tutorial we will learn how to share text of a TextView on button click. When the button is clicked bottom sheet will appear listing the apps that can share that text...
Share text of TextView on button click (Kotlin) - Android Studio

Step 2: Code

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView"
        android:textAlignment="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="This is the text to be shared..." />

    <Button
        android:id="@+id/btnShare"
        android:text="Share Text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.kt
package com.blogspot.devofandroid.myapplication

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btnShare.setOnClickListener {
            //Get text from TextView and store in variable "s"
            val s = textView.text.toString()
            //Intent to share the text
            val shareIntent = Intent()
            shareIntent.action = Intent.ACTION_SEND
            shareIntent.type="text/plain"
            shareIntent.putExtra(Intent.EXTRA_TEXT, s);
            startActivity(Intent.createChooser(shareIntent,"Share via"))
        }


    }
}

Step 3: Output

Share text of TextView on button click (Kotlin) - Android Studio
Share text of TextView on button click (Kotlin) - Android Studio
Share text of TextView on button click (Kotlin) - Android Studio
Share text of TextView on button click (Kotlin) - Android Studio


Comments

Popular posts from this blog

Picture In Picture | Android Studio | Kotlin

Manage External Storage Permission | Android Studio | Kotlin

Add a Back Button to Action Bar Android Studio (Kotlin)