How to disable cursor positioning and text selection in an EditText? (Android)

本文介绍了一个自定义Android EditText组件的方法,该方法通过重写onSelectionChanged方法限制了用户在EditText内的光标移动范围,并阻止了文本的选择。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

防止用户在任何地方移动光标位置。光标应始终停留在当前EditText某段选中文本位置。除此之外,用户不应该能够在EditText中选择任何内容。你有什么想法如何实现在Android中使用EditText?

public class CustomEditText extends EditText {

    private CustomSelectionChangedListener listener;

    @Override
    public void onSelectionChanged(int start, int end) {

        if (start != -1 && end != -1) {
            if (listener != null) {
                start = end;
                // 如果监听不为空,需要自行处理setSelection
                listener.onSelectionChanged(start, end);
                return;
            } 
        }
        super.onSelectionChanged(start, end);
    }

    public void setListener(CustomSelectionChangedListener listener) {
        this.listener = listener;
    }
}

重写onSelectionChanged方法,在监听器中通过textView.setSelection控制光标位置。

mEditText.setListener(new CustomSelectionChangedListener() {
                @Override
                public void onSelectionChanged(int start, int end) {          
                    //选中的文本起始和结束位置,注意 selectedStart 和 selectedEnd大于等于0
                    int selectedStart = xxx; 
                    int selectedEnd = xxx;

                    if (selectedEnd < selectedStart) {
                        selectedEnd = selectedStart;
                    }
                    if (start >= selectedStart && end <= selectedEnd) {
                        start = end;
                        mEditText.setSelection(start, end);
                    } else if (start < selectedStart){
                        mEditText.setSelection(selectedStart);
                    } else if (end > selectedEnd) {
                        mEditText.setSelection(selectedEnd);
                    }

                }
            });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值