如何解决使用bool在Kotlin中自动显示/关闭警报对话框
我正在创建一个文本语音转换应用,希望在tts对象讲话时向扬声器显示一个对话框,并在完成后自动隐藏自己。有人有办法做到吗?下面是我目前为止的想法,
private lateinit var textToSpeech: TextToSpeech
private lateinit var alertDialogBuilder: AlertDialog.Builder
class MainActivity : AppCompatActivity() {
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
alertDialogBuilder = AlertDialog.Builder(this)
textToSpeech = TextToSpeech(applicationContext,TextToSpeech.OnInitListener {})
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun speakToMe(view: View) {
alertDialogBuilder.setMessage("I'm speaking!")
alertDialogBuilder.show()
val charSeq = "Well hello there!" as CharSequence
textToSpeech.speak(charSeq,TextToSpeech.QUEUE_FLUSH,null,"")
while (!textToSpeech.isSpeaking){
// alertDialogBuilder.dismiss() or some other fun I can't seem to find
}
}
}
解决方法
您需要像这样将进度侦听器添加到tts:
val params = Bundle()
params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,text)
tts.setOnUtteranceProgressListener(object : UtteranceProgressListener(){
override fun onDone(p0: String?) {
//dismiss the AlertDialog here (has to run on UI Thread)
}
override fun onError(p0: String?) {
}
override fun onStart(p0: String?) {
//show the AlertDialog here (has to run on UI Thread)
}
})
tts.speak(text,TextToSpeech.QUEUE_FLUSH,params,"UtterID")
BEAR IN MIND,“ UtterID”(可以是您想要的任何东西)对于侦听器的功能至关重要。
,您不能在主线程中以这种方式使用while
,因为它将锁定UI并获得ANR(应用程序不响应崩溃)。
开始讲话时,给它一个ID,然后添加一个侦听器以响应结果由于该侦听器可能是在另一个线程上调用的,因此必须使用runOnUiThread
或协程返回再次操作用户界面的主线程。
调用dialogBuilder.show()
时,请存储返回的AlertDialog,以便以后将其关闭。
顺便说一句,没有理由将String强制转换为CharSequence。您可以将其传递给函数,编译器会将其识别为CharSequence。
fun speakToMe(view: View) {
alertDialogBuilder.setMessage("I'm speaking!")
val dialog = alertDialogBuilder.show()
val charSeq = "Well hello there!"
val id = "speechId"
textToSpeech.speak(charSeq,null,id)
textToSpeech.onUtteranceProgressListener = object: UtteranceProgressListener {
override fun onDone(utteranceId: String) {
if (id == utteranceId) {
runOnUiThread { dialog.dismiss() }
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。