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...
Step 1: Create a new project OR Open your project
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")) } } }
Comments
Post a Comment