139

在我的应用程序中,有一个注册屏幕,我不希望用户能够将文本复制/粘贴到该EditText字段中。我onLongClickListener在每个上都设置了一个,EditText因此不会显示显示复制/粘贴/输入方法和其他选项的上下文菜单。因此用户将无法复制/粘贴到编辑字段中。

 OnLongClickListener mOnLongClickListener = new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            // prevent context menu from being popped up, so that user
            // cannot copy/paste from/into any EditText fields.
            return true;
        }
    };

但是,如果用户启用了 Android 默认以外的第三方键盘,可能会出现问题,该键盘可能具有复制/粘贴按钮或可能显示相同的上下文菜单。那么如何在那种情况下禁用复制/粘贴?

如果还有其他方法可以复制/粘贴,请告诉我。(以及可能如何禁用它们)

任何帮助,将不胜感激。

4

30 回答 30

140

最好的方法是使用:

etUsername.setLongClickable(false);
于 2012-12-11T13:15:47.780 回答
119

如果您使用 API 级别 11 或更高版本,则可以停止复制、粘贴、剪切和自定义上下文菜单的出现。

edittext.setCustomSelectionActionModeCallback(new ActionMode.Callback() {

            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public void onDestroyActionMode(ActionMode mode) {                  
            }

            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                return false;
            }
        });

从 onCreateActionMode(ActionMode, Menu) 返回 false 将阻止启动操作模式(全选、剪切、复制和粘贴操作)。

于 2012-09-08T14:02:29.160 回答
53

您可以通过禁用 EditText 的长按来做到这一点

要实现它,只需在 xml 中添加以下行 -

android:longClickable="false"
于 2014-09-25T01:23:45.560 回答
38

我可以使用以下方法禁用复制和粘贴功能:

textField.setCustomSelectionActionModeCallback(new ActionMode.Callback() {

    public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
        return false;
    }

    public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
        return false;
    }

    public boolean onActionItemClicked(ActionMode actionMode, MenuItem item) {
        return false;
    }

    public void onDestroyActionMode(ActionMode actionMode) {
    }
});

textField.setLongClickable(false);
textField.setTextIsSelectable(false);

希望对你有帮助 ;-)

于 2012-09-06T05:56:01.257 回答
14

Kotlin 解决方案:

fun TextView.disableCopyPaste() {
    isLongClickable = false
    setTextIsSelectable(false)
    customSelectionActionModeCallback = object : ActionMode.Callback {
        override fun onCreateActionMode(mode: ActionMode?, menu: Menu): Boolean {
            return false
        }

        override fun onPrepareActionMode(mode: ActionMode?, menu: Menu): Boolean {
            return false
        }

        override fun onActionItemClicked(mode: ActionMode?, item: MenuItem): Boolean {
            return false
        }

        override fun onDestroyActionMode(mode: ActionMode?) {}
    }
}

然后你可以简单地调用你的这个方法TextView

override fun onCreate() {
    priceEditText.disableCopyPaste()
}
于 2017-07-20T17:51:04.730 回答
12

这是在所有版本中禁用editText工作的剪切复制粘贴的最佳方法

if (android.os.Build.VERSION.SDK_INT < 11) {
        editText.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v,
                    ContextMenuInfo menuInfo) {
                // TODO Auto-generated method stub
                menu.clear();
            }
        });
    } else {
        editText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {

            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                // TODO Auto-generated method stub
                return false;
            }

            public void onDestroyActionMode(ActionMode mode) {
                // TODO Auto-generated method stub

            }

            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                // TODO Auto-generated method stub
                return false;
            }

            public boolean onActionItemClicked(ActionMode mode,
                    MenuItem item) {
                // TODO Auto-generated method stub
                return false;
            }
        });
    }
于 2014-03-31T08:09:37.170 回答
11

除了setCustomSelectionActionModeCallback禁用长按解决方案外,还必须防止在单击文本选择句柄时出现 PASTE/REPLACE 菜单,如下图所示:

带有粘贴菜单的文本选择句柄

解决方案在于防止 PASTE/REPLACE 菜单出现在show()(未记录的)android.widget.Editor类的方法中。在菜单出现之前,对 进行检查if (!canPaste && !canSuggest) return;。用作设置这些变量的基础的两种方法都在EditText类中:

更完整的答案可在此处获得

于 2015-03-06T07:08:14.983 回答
6

如果您不想禁用长按,因为您需要在长按时执行某些功能,而不是返回 true 是一个更好的选择。

你的edittext长按会是这样的。

edittext.setOnLongClickListener(new View.OnLongClickListener() {
      @Override
      public boolean onLongClick(View v) {
            //  Do Something or Don't
            return true;
      }
});

根据文档, 返回“True”将表示已处理长点击,因此无需执行默认操作。

我在 API 级别 16、22 和 25 上对此进行了测试。它对我来说工作正常。希望这会有所帮助。

于 2017-07-24T08:07:14.140 回答
4

这是禁用“粘贴”弹出窗口的技巧。您必须覆盖EditText方法:

@Override
public int getSelectionStart() {
    for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
        if (element.getMethodName().equals("canPaste")) {
            return -1;
        }
    }
    return super.getSelectionStart();
}

可以对其他动作进行类似的操作。

于 2017-01-19T22:11:50.697 回答
4

我已经测试过这个解决方案并且这个工作

    mSubdomainEditText.setLongClickable(false);
    mSubdomainEditText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {

      public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false;
      }

      public void onDestroyActionMode(ActionMode mode) {
      }

      public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        return false;
      }

      public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        return false;
      }
    });
于 2019-08-03T23:00:06.490 回答
3

https://github.com/neopixl/PixlUI提供了一个EditTextwith 方法

myEditText.disableCopyAndPaste().

它适用于旧 API

于 2013-11-14T16:28:32.323 回答
3

我在Kotlin语言中添加了扩展功能:

fun EditText.disableTextSelection() {
    this.setCustomSelectionActionModeCallback(object : android.view.ActionMode.Callback {
        override fun onActionItemClicked(mode: android.view.ActionMode?, item: MenuItem?): Boolean {
            return false
        }
        override fun onCreateActionMode(mode: android.view.ActionMode?, menu: Menu?): Boolean {
            return false
        }
        override fun onPrepareActionMode(mode: android.view.ActionMode?, menu: Menu?): Boolean {
            return false
        }
        override fun onDestroyActionMode(mode: android.view.ActionMode?) {
        }
    })
}

你可以像这样使用它:

edit_text.disableTextSelection()

还在您的 xml 中添加了以下行:

                android:longClickable="false"
                android:textIsSelectable="false"
于 2020-06-10T06:56:02.130 回答
2

@Zain Ali,您的答案适用于 API 11。我只是想建议一种在 API 10 上进行操作的方法。由于我必须在那个版本上维护我的项目 API,我一直在使用 2.3.3 中可用的功能并且有可能做到这一点。我已经分享了下面的片段。我测试了代码,它对我有用。我迫不及待地做了这个片段。如果可以进行任何更改,请随时改进代码..

// A custom TouchListener is being implemented which will clear out the focus 
// and gain the focus for the EditText, in few milliseconds so the selection 
// will be cleared and hence the copy paste option wil not pop up.
// the respective EditText should be set with this listener 
// tmpEditText.setOnTouchListener(new MyTouchListener(tmpEditText, tmpImm));

public class MyTouchListener implements View.OnTouchListener {

    long click = 0;
    EditText mEtView;
    InputMethodManager imm;

    public MyTouchListener(EditText etView, InputMethodManager im) {
        mEtView = etView;
        imm = im;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            long curr = System.currentTimeMillis();
            if (click !=0 && ( curr - click) < 30) {

                mEtView.setSelected(false);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mEtView.setSelected(true);
                        mEtView.requestFocusFromTouch();
                        imm.showSoftInput(mEtView, InputMethodManager.RESULT_SHOWN);
                    }
                },25);

            return true;
            }
            else {
                if (click == 0)
                    click = curr;
                else
                    click = 0;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mEtView.requestFocusFromTouch();
                        mEtView.requestFocusFromTouch();
                        imm.showSoftInput(mEtView, InputMethodManager.RESULT_SHOWN);
                    }
                },25);
            return true;
            }

        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            mEtView.setSelected(false);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mEtView.setSelected(true);
                    mEtView.requestFocusFromTouch();
                    mEtView.requestFocusFromTouch();
                    imm.showSoftInput(mEtView, InputMethodManager.RESULT_SHOWN);
                }
            },25);
            return true;
        }
        return false;
    }
于 2012-10-12T14:29:27.053 回答
2

如果要禁用ActionMode复制/粘贴,则需要覆盖 2 个回调。这适用于TextViewEditText(或TextInputEditText

import android.view.ActionMode

fun TextView.disableCopyPaste() {
  isLongClickable = false
  setTextIsSelectable(false)
  customSelectionActionModeCallback = object : ActionMode.Callback {
    override fun onCreateActionMode(mode: ActionMode?, menu: Menu) = false
    override fun onPrepareActionMode(mode: ActionMode?, menu: Menu) = false
    override fun onActionItemClicked(mode: ActionMode?, item: MenuItem) = false
    override fun onDestroyActionMode(mode: ActionMode?) {}
  }
  //disable action mode when edittext gain focus at first
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    customInsertionActionModeCallback = object : ActionMode.Callback {
      override fun onCreateActionMode(mode: ActionMode?, menu: Menu) = false
      override fun onPrepareActionMode(mode: ActionMode?, menu: Menu) = false
      override fun onActionItemClicked(mode: ActionMode?, item: MenuItem) = false
      override fun onDestroyActionMode(mode: ActionMode?) {}
    }
  }
}

这个扩展基于@Alexandr 解决方案,对我来说效果很好。

于 2020-11-18T08:35:47.740 回答
1

阅读剪贴板,检查输入和输入“键入”的时间。如果剪贴板有相同的文本并且速度太快,请删除粘贴的输入。

于 2011-11-14T08:33:38.050 回答
1

解决方案很简单

public class MainActivity extends AppCompatActivity {

EditText et_0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    et_0 = findViewById(R.id.et_0);

    et_0.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            //to keep the text selection capability available ( selection cursor)
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            //to prevent the menu from appearing
            menu.clear();
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {

        }
    });
   }
}

--------> 预览 <---------

于 2018-07-07T10:21:53.417 回答
1

尝试关注客户类以进行预防复制和粘贴Edittext

public class SegoeUiEditText extends AppCompatEditText {
private final Context context;


@Override
public boolean isSuggestionsEnabled() {
    return false;
}
public SegoeUiEditText(Context context) {
    super(context);
    this.context = context;
    init();
}

public SegoeUiEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
    init();
}

public SegoeUiEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    this.context = context;
    init();
}


private void setFonts(Context context) {
    this.setTypeface(Typeface.createFromAsset(context.getAssets(), "Fonts/Helvetica-Normal.ttf"));
}

private void init() {

        setTextIsSelectable(false);
        this.setCustomSelectionActionModeCallback(new ActionModeCallbackInterceptor());
        this.setLongClickable(false);

}
@Override
public int getSelectionStart() {

    for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
        if (element.getMethodName().equals("canPaste")) {
            return -1;
        }
    }
    return super.getSelectionStart();
}
/**
 * Prevents the action bar (top horizontal bar with cut, copy, paste, etc.) from appearing
 * by intercepting the callback that would cause it to be created, and returning false.
 */
private class ActionModeCallbackInterceptor implements ActionMode.Callback, android.view.ActionMode.Callback {
    private final String TAG = SegoeUiEditText.class.getSimpleName();

    public boolean onCreateActionMode(ActionMode mode, Menu menu) { return false; }
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; }
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return false; }
    public void onDestroyActionMode(ActionMode mode) {}

    @Override
    public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
        return false;
    }

    @Override
    public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
        menu.clear();
        return false;
    }

    @Override
    public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {
        return false;
    }

    @Override
    public void onDestroyActionMode(android.view.ActionMode mode) {

    }
}

}

于 2018-08-10T19:53:24.247 回答
1

对于带有剪贴板的智能手机,可以防止这样。

editText.setFilters(new InputFilter[]{new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (source.length() > 1) {
                return "";
            }  return null;
        }
    }});
于 2018-12-18T10:48:01.417 回答
0

我发现当您创建输入过滤器以避免输入不需要的字符时,将这些字符粘贴到编辑文本中没有任何效果。所以这种方式也解决了我的问题。

于 2011-11-23T03:54:11.847 回答
0

对我有用的解决方案是创建自定义 Edittext 并覆盖以下方法:

public class MyEditText extends EditText {

private int mPreviousCursorPosition;

@Override
protected void onSelectionChanged(int selStart, int selEnd) {
    CharSequence text = getText();
    if (text != null) {
        if (selStart != selEnd) {
            setSelection(mPreviousCursorPosition, mPreviousCursorPosition);
            return;
        }
    }
    mPreviousCursorPosition = selStart;
    super.onSelectionChanged(selStart, selEnd);
}

}

于 2017-01-13T13:50:48.310 回答
0

尝试使用。

myEditext.setCursorVisible(false);

       myEditext.setCustomSelectionActionModeCallback(new ActionMode.Callback() {

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // TODO Auto-generated method stub
            return false;
        }

        public void onDestroyActionMode(ActionMode mode) {
            // TODO Auto-generated method stub

        }

        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // TODO Auto-generated method stub
            return false;
        }

        public boolean onActionItemClicked(ActionMode mode,
                MenuItem item) {
            // TODO Auto-generated method stub
            return false;
        }
    });
于 2018-01-25T13:23:05.403 回答
0

谁在 Kotlin 中寻找解决方案,使用下面的类作为自定义小部件并在 xml 中使用它。

类 SecureEditText : TextInputEditText {

/** This is a replacement method for the base TextView class' method of the same name. This method
 * is used in hidden class android.widget.Editor to determine whether the PASTE/REPLACE popup
 * appears when triggered from the text insertion handle. Returning false forces this window
 * to never appear.
 * @return false
 */
override fun isSuggestionsEnabled(): Boolean {
    return false
}

override fun getSelectionStart(): Int {
    for (element in Thread.currentThread().stackTrace) {
        if (element.methodName == "canPaste") {
            return -1
        }
    }
    return super.getSelectionStart()
}

public override fun onSelectionChanged(start: Int, end: Int) {

    val text = text
    if (text != null) {
        if (start != text.length || end != text.length) {
            setSelection(text.length, text.length)
            return
        }
    }

    super.onSelectionChanged(start, end)
}

companion object {
    private val EDITTEXT_ATTRIBUTE_COPY_AND_PASTE = "isCopyPasteDisabled"
    private val PACKAGE_NAME = "http://schemas.android.com/apk/res-auto"
}

constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
    disableCopyAndPaste(context, attrs)
}

/**
 * Disable Copy and Paste functionality on EditText
 *
 * @param context Context object
 * @param attrs   AttributeSet Object
 */
private fun disableCopyAndPaste(context: Context, attrs: AttributeSet) {
    val isDisableCopyAndPaste = attrs.getAttributeBooleanValue(
        PACKAGE_NAME,
        EDITTEXT_ATTRIBUTE_COPY_AND_PASTE, true
    )
    if (isDisableCopyAndPaste && !isInEditMode()) {
        val inputMethodManager =
            context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        this.setLongClickable(false)
        this.setOnTouchListener(BlockContextMenuTouchListener(inputMethodManager))
    }
}

/**
 * Perform Focus Enabling Task to the widget with the help of handler object
 * with some delay
 * @param inputMethodManager is used to show the key board
 */
private fun performHandlerAction(inputMethodManager: InputMethodManager) {
    val postDelayedIntervalTime: Long = 25
    Handler().postDelayed(Runnable {
        this@SecureEditText.setSelected(true)
        this@SecureEditText.requestFocusFromTouch()
        inputMethodManager.showSoftInput(
            this@SecureEditText,
            InputMethodManager.RESULT_SHOWN
        )
    }, postDelayedIntervalTime)
}

/**
 * Class to Block Context Menu on double Tap
 * A custom TouchListener is being implemented which will clear out the focus
 * and gain the focus for the EditText, in few milliseconds so the selection
 * will be cleared and hence the copy paste option wil not pop up.
 * the respective EditText should be set with this listener
 *
 * @param inputMethodManager is used to show the key board
 */
private inner class BlockContextMenuTouchListener internal constructor(private val inputMethodManager: InputMethodManager) :
    View.OnTouchListener {
    private var lastTapTime: Long = 0
    val TIME_INTERVAL_BETWEEN_DOUBLE_TAP = 30
    override fun onTouch(v: View, event: MotionEvent): Boolean {
        if (event.getAction() === MotionEvent.ACTION_DOWN) {
            val currentTapTime = System.currentTimeMillis()
            if (lastTapTime != 0L && currentTapTime - lastTapTime < TIME_INTERVAL_BETWEEN_DOUBLE_TAP) {
                this@SecureEditText.setSelected(false)
                performHandlerAction(inputMethodManager)
                return true
            } else {
                if (lastTapTime == 0L) {
                    lastTapTime = currentTapTime
                } else {
                    lastTapTime = 0
                }
                performHandlerAction(inputMethodManager)
                return true
            }
        } else if (event.getAction() === MotionEvent.ACTION_MOVE) {
            this@SecureEditText.setSelected(false)
            performHandlerAction(inputMethodManager)
        }
        return false
    }
}

}

于 2020-01-14T12:49:10.383 回答
0

一个广泛兼容的解决方案(从 Android 1.5 开始)是

@Override
public boolean onTextContextMenuItem(int id) {
    switch (id){
        case android.R.id.cut:
            onTextCut();
            return false;
        case android.R.id.paste:
            onTextPaste();
            return false;
        case android.R.id.copy:
            onTextCopy();
            return false;
    }
    return true;
}
于 2021-03-23T14:51:48.743 回答
0

在花了很多时间后,删除了 EditText 的ContextMenu中的粘贴选项,我在 Java 中遵循了以下代码。

NoMenuEditText.Java

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import androidx.appcompat.widget.AppCompatEditText;

/**
 * custom edit text
 */


public class NoMenuEditText extends AppCompatEditText {

    private static final String EDITTEXT_ATTRIBUTE_COPY_AND_PASTE = "isCopyPasteDisabled";
    private static final String PACKAGE_NAME = "http://schemas.android.com/apk/res-auto";

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

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

    /**
     * Enable/Disable Copy and Paste functionality on EditText
     *
     * @param context Context object
     * @param attrs   AttributeSet Object
     */
    private void EnableDisableCopyAndPaste(Context context, AttributeSet attrs) {
        boolean isDisableCopyAndPaste = attrs.getAttributeBooleanValue(PACKAGE_NAME,
                EDITTEXT_ATTRIBUTE_COPY_AND_PASTE, false);
        if (isDisableCopyAndPaste && !isInEditMode()) {
            InputMethodManager inputMethodManager = (InputMethodManager)
                    context.getSystemService(Context.INPUT_METHOD_SERVICE);
            this.setLongClickable(false);
            this.setOnTouchListener(new BlockContextMenuTouchListener
                    (inputMethodManager));
        }
    }

    /**
     * Perform Focus Enabling Task to the widget with the help of handler object
     * with some delay
     */
    private void performHandlerAction(final InputMethodManager inputMethodManager) {
        int postDelayedIntervalTime = 25;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                NoMenuEditText.this.setSelected(true);
                NoMenuEditText.this.requestFocusFromTouch();
                inputMethodManager.showSoftInput(NoMenuEditText.this,
                        InputMethodManager.RESULT_SHOWN);
            }
        }, postDelayedIntervalTime);
    }

    /**
     * Class to Block Context Menu on double Tap
     * A custom TouchListener is being implemented which will clear out the focus
     * and gain the focus for the EditText, in few milliseconds so the selection
     * will be cleared and hence the copy paste option wil not pop up.
     * the respective EditText should be set with this listener
     */
    private class BlockContextMenuTouchListener implements View.OnTouchListener {
        private static final int TIME_INTERVAL_BETWEEN_DOUBLE_TAP = 30;
        private InputMethodManager inputMethodManager;
        private long lastTapTime = 0;

        BlockContextMenuTouchListener(InputMethodManager inputMethodManager) {
            this.inputMethodManager = inputMethodManager;
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                long currentTapTime = System.currentTimeMillis();
                if (lastTapTime != 0 && (currentTapTime - lastTapTime)
                        < TIME_INTERVAL_BETWEEN_DOUBLE_TAP) {
                    NoMenuEditText.this.setSelected(false);
                    performHandlerAction(inputMethodManager);
                    return true;
                } else {
                    if (lastTapTime == 0) {
                        lastTapTime = currentTapTime;
                    } else {
                        lastTapTime = 0;
                    }
                    performHandlerAction(inputMethodManager);
                    return true;
                }
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                NoMenuEditText.this.setSelected(false);
                performHandlerAction(inputMethodManager);
            }
            return false;
        }
    }

    @Override
    protected void onSelectionChanged(int selStart, int selEnd) {
        CharSequence text = getText();
        if (text != null) {
            if (selStart != text.length() || selEnd != text.length()) {
                setSelection(text.length(), text.length());
                return;
            }
        }
        super.onSelectionChanged(selStart, selEnd);
    }


    @Override
    public boolean isSuggestionsEnabled() {
        return false;
    }

    @Override
    public int getSelectionStart() {
        for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
            if (element.getMethodName().equals("canPaste")) {
                return -1;
            }
        }
        return super.getSelectionStart();
    }



}

主要活动

import androidx.appcompat.app.AppCompatActivity;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    NoMenuEditText edt_username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edt_username = (NoMenuEditText) findViewById(R.id.edt_username);

   
        edt_username.setLongClickable(false);
        edt_username.setTextIsSelectable(false);

        edt_username.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
            @Override
            public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
                return false;

            }

            @Override
            public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
                return false;
            }

            @Override
            public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {

                return false;
            }

            @Override
            public void onDestroyActionMode(ActionMode actionMode) {

            }
        });
        
    }

}

可绘制-zeropx.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <size
        android:width="0dp"
        android:height="0dp"/>

</shape>

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="NoMenuEditText">
        <attr name="isCopyPasteDisabled" format="boolean" />
    </declare-styleable>
</resources>

最后,我终于从EditText的上下文菜单中删除了粘贴选项

谢谢StackOverflow 帖子http://androidinformative.com/disabling-context-menu/

于 2021-08-24T18:37:29.513 回答
0
 editText.apply {
        setOnTouchListener { v, event ->
               if (event.action == KeyEvent.ACTION_DOWN) {
                      requestFocus()
                      setSelection(text.toString().length)
                      showKeyboard()
                      return@setOnTouchListener true
               }
        }
 }

fun View.showKeyboard() {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(this, 0)
 }
于 2021-10-03T21:00:13.233 回答
0

上述解决方案未考虑使用硬件键盘 (Ctrl+v) 进行粘贴。最简单的解决方案是在您的 EditText 上设置一个 TextWatcher,并在 afterTextChanged 方法中过滤您想要或不想要的字符。这适用于所有情况,即键入的字符、粘贴、自动建议和自动更正。

于 2021-11-16T18:31:32.480 回答
0

实际上,在我的情况下,我必须为选择插入设置回调,然后我才让复制/粘贴弹出窗口不再出现。像这样的东西:

 private void disableCopyPaste() {
    input.setLongClickable(false);
    input.setTextIsSelectable(false);
    final ActionMode.Callback disableCopyPasteCallback = new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
            return false;
        }
        @Override
        public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {
        }
    };
    input.setCustomSelectionActionModeCallback(disableCopyPasteCallback);
    input.setCustomInsertionActionModeCallback(disableCopyPasteCallback);
}
于 2022-02-03T09:07:50.687 回答
0

与其完全禁用 EditText 上的所有操作,不如只阻止某些操作(如剪切/复制,但不粘贴):

/**
 * Prevent copy/cut of the (presumably sensitive) contents of this TextView.
 */
fun TextView.disableCopyCut() {
    setCustomSelectionActionModeCallback(
        object : Callback {
            override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?) = false

            override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
                menu?.apply {
                    removeItem(android.R.id.copy)
                    removeItem(android.R.id.cut)
                }
                return true
            }

            override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?) = false

            override fun onDestroyActionMode(mode: ActionMode?) {
                // no-op
            }
        }
    )
}

可以选择性删除的操作:

removeItem(android.R.id.copy)
removeItem(android.R.id.cut)
removeItem(android.R.id.paste)
removeItem(android.R.id.shareText) // Share
removeItem(android.R.id.textAssist) // Open with Chrome
于 2022-02-21T00:35:47.177 回答
-1

与 GnrlKnowledge 类似,可以清除剪贴板

http://developer.android.com/reference/android/text/ClipboardManager.html

如果需要,将文本保留在剪贴板中,在 onDestroy 上,您可以再次设置它。

于 2011-11-23T02:16:03.313 回答
-1

你可以试试 android:focusableInTouchMode="false"。

于 2016-04-20T15:18:25.950 回答