CopyTextView.java

 1package eu.siacs.conversations.ui.widget;
 2
 3import android.annotation.TargetApi;
 4import android.content.ClipData;
 5import android.content.ClipboardManager;
 6import android.content.Context;
 7import android.os.Build;
 8import android.util.AttributeSet;
 9import android.widget.TextView;
10
11public class CopyTextView extends TextView {
12
13	public CopyTextView(Context context) {
14		super(context);
15	}
16
17	public CopyTextView(Context context, AttributeSet attrs) {
18		super(context, attrs);
19	}
20
21	public CopyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
22		super(context, attrs, defStyleAttr);
23	}
24
25	@SuppressWarnings("unused")
26	@TargetApi(Build.VERSION_CODES.LOLLIPOP)
27	public CopyTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
28		super(context, attrs, defStyleAttr, defStyleRes);
29	}
30
31	public interface CopyHandler {
32		public String transformTextForCopy(CharSequence text, int start, int end);
33	}
34
35	private CopyHandler copyHandler;
36
37	public void setCopyHandler(CopyHandler copyHandler) {
38		this.copyHandler = copyHandler;
39	}
40
41	@Override
42	public boolean onTextContextMenuItem(int id) {
43		CharSequence text = getText();
44		int min = 0;
45		int max = text.length();
46		if (isFocused()) {
47			final int selStart = getSelectionStart();
48			final int selEnd = getSelectionEnd();
49			min = Math.max(0, Math.min(selStart, selEnd));
50			max = Math.max(0, Math.max(selStart, selEnd));
51		}
52		String textForCopy = null;
53		if (id == android.R.id.copy && copyHandler != null) {
54			textForCopy = copyHandler.transformTextForCopy(getText(), min, max);
55		}
56		try {
57			return super.onTextContextMenuItem(id);
58		} finally {
59			if (textForCopy != null) {
60				ClipboardManager clipboard = (ClipboardManager) getContext().
61						getSystemService(Context.CLIPBOARD_SERVICE);
62				clipboard.setPrimaryClip(ClipData.newPlainText(null, textForCopy));
63			}
64		}
65	}
66}