Implement Copy to Clipboard button in Android App
In this post, I will show you how to create a button called Copy to Clipboard in your Android app.
For that, We use an EditText for text selection and copy and a Button to copy the text to Clipboard.
In our MainActivity.XML file, we create an EditText and Button.
<?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:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/Edittext"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="copy"
android:id="@+id/Button"
app:layout_constraintTop_toBottomOf="@id/Edittext"/>
</androidx.constraintlayout.widget.ConstraintLayout>
In this, we use EditText to get value and a Button to Copy that value to Clipboard.MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText et;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = findViewById(R.id.Edittext);
btn = findViewById(R.id.Button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String copy = et.getText().toString();
ClipboardManager clipmanager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Label",copy);
clipmanager.setPrimaryClip(clip);
Toast.makeText(MainActivity.this, "Copied to Clipboard", Toast.LENGTH_SHORT).show();
}
});
}
}
In this, we find ids of EditText and Button.
Then click on Button will get value from EditText and then call Clipboard Manager to copy that text.
Follow us for more posts like this,
Subscribe Harpreet studio on Youtube
Like Harpreet Studio on Facebook
No comments