在我的主片段中,我已经实现了TextToSpeech mainFragment extends Fragment implements TextToSpeech.OnInitListener
。
文本到语音转换工作正常,我还添加了一个工作正常的UtteranceProgressListener
。
我的问题 :我无法调用任何自定义函数,例如gotoNextChapter()
,甚至无法调用简单的Toaster
。获取错误Can't create handler inside thread that has not called Looper.prepare()
欢迎任何建议或解决方案。
我的代码片段:
UtteranceProgressListener SpeechListener = new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
Toast.makeText(getActivity(),utteranceId, Toast.LENGTH_LONG).show();
}
@Override
public void onDone(String utteranceId) {
Toast.makeText(getActivity(),utteranceId, Toast.LENGTH_LONG).show();
gotoNextChapter(); <====function I want to call
read_mode = 0;
}
@Override
public void onError(String utteranceId) {
Toast.makeText(getActivity(),utteranceId, Toast.LENGTH_LONG).show();
}
};
设置语句完成侦听器:
myTTS.setOnUtteranceProgressListener(SpeechListener);
错误我得到:
Caught a RuntimeException from the binder stub implementation.
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at
android.os.Handler.<init>(Handler.java:209)
at
android.os.Handler.<init>(Handler.java:123)
at
android.widget.Toast$TN.<init>(Toast.java:350)
at
android.widget.Toast.<init>(Toast.java:106)
at
android.widget.Toast.makeText(Toast.java:264)
at com.MainActivity$Read$10.onDone(MainActivity.java:1252)
好的,我有一个解决方案,现在我的问题似乎微不足道
我更新的代码如下所示:
@Override
public void onDone(String utteranceId) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getContext(),utteranceId,Toast.LENGTH_LONG).show();
gotoNextChapter(); <====function I want to call
read_mode = 0;
}
});
}
感谢这里的这些家伙:文字转语音说完安卓后我怎么能吐司以及我们什么时候需要在安卓应用程序中使用 runOnUiThread?
如果您在"活动"中:
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(),"...", Toast.LENGTH_LONG).show();
}
});
如果您在片段中:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(),"...", Toast.LENGTH_LONG).show();
}
});
否则,您可以这样做:
Handler mainHandler = new Handler(context.getMainLooper());
Runnable myRunnable = new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(),"...", Toast.LENGTH_LONG).show();
}
};
mainHandler.post(myRunnable);