|
| 1 | +package org.schabi.newpipe.views; |
| 2 | + |
| 3 | +import android.content.Context; |
| 4 | +import android.text.Selection; |
| 5 | +import android.text.Spannable; |
| 6 | +import android.util.AttributeSet; |
| 7 | + |
| 8 | +import androidx.annotation.NonNull; |
| 9 | +import androidx.annotation.Nullable; |
| 10 | +import androidx.appcompat.widget.AppCompatEditText; |
| 11 | + |
| 12 | +import org.schabi.newpipe.util.external_communication.ShareUtils; |
| 13 | + |
| 14 | +public class NewPipeEditText extends AppCompatEditText { |
| 15 | + public NewPipeEditText(@NonNull final Context context) { |
| 16 | + super(context); |
| 17 | + } |
| 18 | + |
| 19 | + public NewPipeEditText(@NonNull final Context context, @Nullable final AttributeSet attrs) { |
| 20 | + super(context, attrs); |
| 21 | + } |
| 22 | + |
| 23 | + public NewPipeEditText(@NonNull final Context context, |
| 24 | + @Nullable final AttributeSet attrs, |
| 25 | + final int defStyleAttr) { |
| 26 | + super(context, attrs, defStyleAttr); |
| 27 | + } |
| 28 | + |
| 29 | + @Override |
| 30 | + public boolean onTextContextMenuItem(final int id) { |
| 31 | + final Spannable text = getText(); |
| 32 | + if (id == android.R.id.shareText) { |
| 33 | + if (text != null) { |
| 34 | + final String selectedText = getSelectedText(text).toString(); |
| 35 | + if (!selectedText.isEmpty()) { |
| 36 | + ShareUtils.shareText(getContext(), "", selectedText); |
| 37 | + } |
| 38 | + Selection.setSelection(text, getSelectionEnd()); |
| 39 | + } |
| 40 | + return true; |
| 41 | + } else { |
| 42 | + return super.onTextContextMenuItem(id); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + @NonNull |
| 47 | + private CharSequence getSelectedText(@NonNull final CharSequence charSequence) { |
| 48 | + int min = 0; |
| 49 | + int max = charSequence.length(); |
| 50 | + |
| 51 | + if (isFocused()) { |
| 52 | + final int selStart = getSelectionStart(); |
| 53 | + final int selEnd = getSelectionEnd(); |
| 54 | + |
| 55 | + min = Math.max(0, Math.min(selStart, selEnd)); |
| 56 | + max = Math.max(0, Math.max(selStart, selEnd)); |
| 57 | + } |
| 58 | + return charSequence.subSequence(min, max); |
| 59 | + } |
| 60 | +} |
0 commit comments