In this post you will learn how to copy and paste android text from edittext, So we will use
ClipboardManager in this tutorial to copy text from edittext in android application and we will
also use ClipData to convert our copied text to plain text in android app.
So let’s start our tutorial by creating new project in android studio.
Now open your activity_main.xml and paste following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/editTextTextPersonName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:ems="10" android:inputType="textPersonName" android:hint="enter some text" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:text="Copy" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/editTextTextPersonName" /> </androidx.constraintlayout.widget.ConstraintLayout> |
Now we need to initialize our views in our java file, So open MainActivity.java and paste the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class MainActivity extends AppCompatActivity { Button btnCopy; EditText etText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnCopy = findViewById(R.id.button); etText = findViewById(R.id.editTextTextPersonName); btnCopy.setOnClickListener(view -> { String output = etText.getText().toString(); if (output.isEmpty()) { Toast.makeText(this, "Please enter some text", Toast.LENGTH_SHORT).show(); }else { ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clipData = ClipData.newPlainText("MyData", output); clipboardManager.setPrimaryClip(clipData); Toast.makeText(this, "Text copied to clipboard", Toast.LENGTH_SHORT).show(); } }); } } |
So our application is ready now run your app and type some text in edittext and try to copy
that text by selecting all text and paste it anywhere you want in your application.
That’s how to copy and paste android text.