cocos EditBox光标移动到中间修改内容后光标总是跳转到最后的问题

在使用EditBox时遇到修改输入内容时每次输入完毕光标就会跳转到最后,经过查询找到大佬给的方案完美解决https://forum.cocos.com/t/1-9-3-editbox/69097,找到安装CocosCreator文件夹修改CocosCreate/CocosCreator/resources/cocos2d-x/cocos/platform/android/java/src/org/cocos2dx/lib路径下Cocos2dxEditBox.java
添加两个私有变量

    private int mCurTextLen = 0;
    private int mForceCursorPos = 0;

    public void setText(String text) {
        String newText = updateDomTextCases(text);
        super.setText(newText);
        this.mCurTextLen = newText.length(); //添加方法
        //this.setSelection(newText.length()); //注释原来的方法
    }

    //新添加方法
    public void forceCursorPos(int forcePos) {
        this.mForceCursorPos = forcePos;
    }

    // 新添加方法
    public void updateCursorPos() {
        int newPos = this.mForceCursorPos < 0 ? 0 : this.mForceCursorPos > this.mCurTextLen ? this.mCurTextLen : this.mForceCursorPos;
        this.setSelection(newPos);
        this.mForceCursorPos = 0;
    }

    Cocos2dxEditBoxHelper.java

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        int selectionStart = editBox.getSelectionStart();
        int selectionEnd = editBox.getSelectionEnd();
        if (selectionStart != selectionEnd || (count > 0 && after > 0)) {
            editBox.forceCursorPos(start + after);
        } else {
            editBox.forceCursorPos(selectionStart - count + after);
        }
    }

    public void afterTextChanged(final Editable s) {
        if (!editBox.getChangedTextProgrammatically()) {
            editBox.removeTextChangedListener(this);
            editBox.setText(editBox.getText().toString());
            editBox.updateCursorPos();          //  在这里更新光标位置
            editBox.addTextChangedListener(this);

            if ((Boolean)editBox.getTag()) {
                mCocos2dxActivity.runOnGLThread(new Runnable() {
                            @Override
                public void run() {
                    Cocos2dxEditBoxHelper.__editBoxEditingChanged(index, s.toString());
                }
            });
        }
    }
    editBox.setChangedTextProgrammatically(false);

}

标签: none

添加新评论