aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/pixart/messenger/ui/widget/CopyTextView.java
blob: 683c65ec00977c8c94dba8fb5437cdfeaa5b7ba6 (plain)
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package de.pixart.messenger.ui.widget;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

@SuppressLint("AppCompatCustomView")
public class CopyTextView extends AppCompatTextView {

    public CopyTextView(Context context) {
        super(context);
    }

    public CopyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CopyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public interface CopyHandler {
        String transformTextForCopy(CharSequence text, int start, int end);
    }

    private CopyHandler copyHandler;

    public void setCopyHandler(CopyHandler copyHandler) {
        this.copyHandler = copyHandler;
    }

    @Override
    public boolean onTextContextMenuItem(int id) {
        final CharSequence text = getText();
        int min = 0;
        int max = text.length();
        if (isFocused()) {
            final int selStart = getSelectionStart();
            final int selEnd = getSelectionEnd();
            min = Math.max(0, Math.min(selStart, selEnd));
            max = Math.max(0, Math.max(selStart, selEnd));
        }
        String textForCopy = null;
        if (id == android.R.id.copy && copyHandler != null) {
            textForCopy = copyHandler.transformTextForCopy(getText(), min, max);
        }
        try {
            return super.onTextContextMenuItem(id);
        } finally {
            if (textForCopy != null) {
                ClipboardManager clipboard = (ClipboardManager) getContext().
                        getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setPrimaryClip(ClipData.newPlainText(null, textForCopy));
            }
        }
    }
}