Android在没有ContextMenu的情况下在TextView / EditText上选择文本

时间:2017-09-17 10:40:26

标签: android

正如我们在选择TextView文字后EditTextContextMenu所知道的那样,我的问题是:如何在没有ContextMenu的情况下选择文字或禁用显示文字?

此代码有效,但导致无法选择文本

public class MyEditText extends AppCompatEditText {
    private final Context mContext;
    private       int     mPreviousCursorPosition;

    public MyEditText(Context context) {
        super(context);
        this.mContext = context;
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
    }

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

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

1 个答案:

答案 0 :(得分:0)

对于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) {
            //This will prevent opening the menu
            return false;
        }

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

进一步阅读: