【问题标题】:EditText's cursor positionEditText 的光标位置
【发布时间】:2010-08-10 16:19:36
【问题描述】:

假设用户在 EditText 中写入了一些文本,然后触摸了屏幕上的其他位置,这导致光标位置发生了变化:如何确定新的光标位置?

【问题讨论】:

    标签: android android-ui


    【解决方案1】:

    简单版:

    myEditText.getSelectionStart();
    

    如果你想对事件做出反应,你可以尝试

    myEditText.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            // view is myEditText here
        }
    });
    

    event 允许区分新闻和发布。

    EditText 也有一个 setOnClickListener() 可能值得一看。

    编辑: 我忘了提到onSelectionChanged(int selStart, int selEnd),如果位置发生变化,selEnd 等于 selStart。

    【讨论】:

    • 澄清:必须在 EditText 子类中覆盖 onSelectionChanged() 才能有用。 OnTouch 事件仅在用户真正触摸屏幕时发生。 OnClick 事件可以在用户触摸屏幕或通过某些物理输入时触发,例如方向键中心、轨迹球点击等
    【解决方案2】:

    最好和安全的方法是使用 TextWatcher

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                    int cursorIndex = start + 1;
            }
    

    【讨论】:

    • 用户可以在不改变文本的情况下移动光标。这种方法在那边没用。
    猜你喜欢
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2018-09-11
    相关资源
    最近更新 更多