我是android编程的新手。所以我有一个ArrayList<String>,我想要在一个循环中讲话,当我单击一个按钮时,语音停止,如果我单击相同的按钮,语音再次开始。
我的布局是这样的:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btnPauseResume"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pause" />
</LinearLayout>我的java代码是这样的:
public class Activity_test extends Activity {
Button btnPauseResume = null;
boolean IsPaused = false;
private TextToSpeech tts = null;
ArrayList<String> Texts = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
btnPauseResume = (Button) findViewById(R.id.btnPauseResume);
Texts = new ArrayList<String>();
btnPauseResume.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Activity_test.this.runOnUiThread(new Runnable() {
@Override
public void run() {
IsPaused = !IsPaused;
if (IsPaused) {
btnPauseResume.setText("Resume");
} else {
btnPauseResume.setText("Pause");
Start();
}
}
});
}
}).start();
}
});
Start();
}
public void Start() {
new Thread(new Runnable() {
public void run() {
Texts.clear();
Texts.add("Long Text 1");
Texts.add("Long Text 2");
Texts.add("Long Text 3");
Speech();
}
}).start();
}
public void Speech() {
tts = new TextToSpeech(Activity_test.this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(Activity_test.this, "This Language is not supported", Toast.LENGTH_SHORT).show();
} else {
for (String Text : Texts) {
if (!IsPaused) {
tts.speak(Text, TextToSpeech.SUCCESS, null);
while (tts.isSpeaking()) {
//wait till speech finish
}
}
}
if (!IsPaused) {
Start();
}
}
} else
Toast.makeText(Activity_test.this, "Initilization Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}在实际代码中,文本的数组列表已更改,因此我调用Speach()方法将新的ArrayList加载到speech中。
所以问题是,当我点击按钮时,它不工作(后退按钮也是如此)。
发布于 2016-02-26 23:58:13
尝试用处理程序和Runnables替换线程。请参阅http://developer.android.com/reference/android/os/Handler.html
我还将确保实际调用了OnClickListener中的代码(使用调试/日志)。
https://stackoverflow.com/questions/35656112
复制相似问题