We -developers- need to make some "copy button" which make our apps more easy-to-use for all people who love cool features or people in a hurry. So let's start coding this cool copy text button feature!
Open you Android Studio, create a new project or use an existing one 😂 then make a button or ImageButton (as you like) to use it as a copy-text-button, and choose a certain EditText View to copy the text content of it.
After that, initialize your views inside the java class like this.
Button copyBtn = findViewById(R.id.copyBtn); EditText toCopy = findViewById(R.id.etCopy);
After getting instance of our view in the java code, we can code the copy to clipboard functionality. Let's do it..
copyBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //the function to copy text to clipboard copy2Clipboard(toCopy.getText().toString()); } });
then we should create the "copy2Clipboard" function like this.
void copy2Clipboard(CharSequence text){ ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("copy text", text); if (clipboard != null){ clipboard.setPrimaryClip(clip); } Toast.makeText(this," text copied", Toast.LENGTH_LONG).show(); }
VOI LAAA! 😄 .. we made it 😎 you can now run your app with this cool feature 😉
Want more posts? check out the new tech blog!