How to Copy Text to Clip Board in Android? - Android Studio
In this tutorial we will learn how to copy text to Clip Board. We will copy the text of TextView when Button is clicked.Step 1: Create a new project OR Open your project
Step 2: Code:
activity_main.xml<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" ><TextViewandroid:id="@+id/textView"android:textAlignment="center"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="This is the text to be copied..." /> <Button android:id="@+id/btnCopy" android:text="Copy Text" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout>
MainActivity.java
package com.blogspot.devofandroid.myapplication;import android.content.ClipboardManager;import android.content.Context;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);final TextView mTextView = findViewById(R.id.textView);Button mBtnCopy = findViewById(R.id.btnCopy);mBtnCopy.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {String s = mTextView.getText().toString();ClipboardManager cb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);cb.setText(s);Toast.makeText(getApplicationContext() , s+"\nCopied" , Toast.LENGTH_SHORT).show();}});}}
0 Response to "Copy Text To Clip Board"