检查编辑文本中的空格键以激活文本到语音

问题描述

我还在读高中,对Kotlin的了解不多,我需要帮助。我有一个切换按钮,可以激活文本到语音引擎的代码。切换按钮时,如果在编辑文本中输入空格(“”),它将激活文本到语音引擎。但是经过几次尝试,我的代码无法正常工作。

val s_type: ToggleButton = findViewById(R.id.st)
    s_type.setonCheckedchangelistener { _,isChecked ->
        if (isChecked) {
            // TOGGLE ENABLED
            input_tts.setonKeyListener(View.OnKeyListener { v,keyCode,event ->
            val text = input_tts.text.toString().trim()
            if(input_tts.text.toString().contains(" "))
                    input_tts.setBackgroundColor(resources.getColor(R.color.colorPrimary))
                    if (input_tts.text != null) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            tts_engine.speak(text,TextToSpeech.QUEUE_FLUSH,null,"tts1")
                        }
                    }
                    false
                })
        }
        else
        {
            //TOGGLE disABLED
        }
    }

如果您能帮助我,并解释一下您的代码的含义,那会很好,因为我对Kotlin的了解并不那么好。谢谢

解决方法

如何使用

EditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s,int start,int count,int after) {
            
        }

        @Override
        public void onTextChanged(CharSequence s,int before,int count) {
            if(s == ' '){//your text here}
        }

        @Override
        public void afterTextChanged(Editable s) {
            attempt[0] = s.toString();
        }
    });