我是java的初学者,我尝试制作我的第一个简单的应用程序,允许用户使用语音与应用程序进行交互,但我在返回speechRecognition的结果时遇到问题。我有以下课程:
class listener implements RecognitionListener{
....
public void onResults(Bundle arg0){
ArrayList<String> matches = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String result = matches.get(0);
}
}
在这种情况下,我想得到
的价值result
我怎样才能获得它的价值?
答案 0 :(得分:1)
class Listener implements RecognitionListener {
....
public String onResults(Bundle arg0) {
ArrayList<String> matches = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
return matches.get(0);
}
}
上面的方法定义如下:
<access modifier> <return type> <method name>(<argument type> <argument name>)
然后该方法可以返回<argument type>
如果返回类型必须为void
,那么您可以执行以下操作:
class Listener implements RecognitionListener {
private String match = null;
....
public void onResults(Bundle arg0) {
ArrayList<String> matches = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
this.match = matches.get(0);
}
/**
* Get the match
* can return null if onResults not called or matches.get(0) == null
*/
public String getMatch() {
return match;
}
}
答案 1 :(得分:1)
保留班级成员并将结果保存在其中:
class listener implements RecognitionListener{
String result;
public void onResults(Bundle arg0){
ArrayList<String> matches = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
result = matches.get(0);
}
}
或者只是在onResult方法中调用你的类的另一个方法:
class listener implements RecognitionListener{
String result;
public void onResults(Bundle arg0){
ArrayList<String> matches = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
doSomethingWithResult(matches.get(0));
}
}