Reputation: 41
I want to copy text from a TextView
to clipboard in API 7.
I have this xml file :
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textColor="#0000ff"
android:textSize="15dp"
android:shadowDx="4"
android:shadowDy="4"
android:shadowRadius="20"
android:textIsSelectable="true"
/>
android:textIsSelectable="true"
has two problems :
TextView
, but when user cuts from TextView
the app fails. Can I do something that the user can't cut the TextView
???Upvotes: 2
Views: 134
Reputation: 2674
In your java code use this :
TextView textView=(TextView)findViewById(R.id.textView1);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(textView.getText());
Toast.makeText(context, "Copied to clipboard", Toast.LENGTH_SHORT).show();
}
});
EDIT- Above code is for click;For long press use below code-
In your onCreate
method register your TextView
for a context menu-
TextView textView=(TextView)findViewById(R.id.textView1);
registerForContextMenu(textView);
Then override onCreateContextMenu
-
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
//user has long pressed your TextView
menu.add(0, v.getId(), 0, "Copy");
//cast the received View to TextView so that you can get its text
TextView textView = (TextView) v;
//place your TextView's text in clipboard
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(textView.getText());
}
Upvotes: 2