EditText: Differentiate between text change by setText() or by keyboard input

前端 未结 5 730
一个人的身影
一个人的身影 2021-01-04 01:58

I have an EditText View which is edited by setText() from my code and by the user via (soft/hard) keyboard and - if possible by speech input. I wan

5条回答
  •  借酒劲吻你
    2021-01-04 02:19

    There are already a lot of good workarounds here! I wanted to add what worked for me to give options to whoever might be having this issue in the future.

    I used the TextWatcher and simply relied on checking for what element currently has focus when the EditText is being edited. Note that this would work if in your app, the user has to give focus to the EditText (by clicking on it for instance) before entering a text, and you're sure that another element will have the focus when you're using setText in your code.

    Something like this

    yourEditText.addTextChangedListener(
                new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
                    }
    
                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        if (yourEditText.hasFocus) {
                            //this is a user input
                        }
                    }
    
                    @Override
                    public void afterTextChanged(Editable s) {
    
                    }
                }
        );
    

提交回复
热议问题