我正在创建一个类似于语音识别准确性游戏的东西,我正在使用一个for循环,其中包含我需要命名的单词,但问题是在开始活动后结果它只是继续运行到下一个单词而没有给你一个有机会回答。我已经看到了两种方法的可能替代方案,一种是回调类(从未做过这样的事情),并且不知何故让它们相互转发,但我不确定它是如何工作的,也无法找到详细的解释。这是我使用for循环的方法
for (int i = 0; i < vocabWords.Length; i++)
{
WordToGuess.Text = vocabWords[i];
CurrWord = vocabWords[i];
textBox.Text = "";
string messageSpeakNow = "Speak";
var voiceIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
voiceIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
voiceIntent.PutExtra(RecognizerIntent.ExtraPrompt, messageSpeakNow);
voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1500);
voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1500);
voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 15000);
voiceIntent.PutExtra(RecognizerIntent.ExtraMaxResults, 1);
voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default);
StartActivityForResult(voiceIntent, VOICE);
}
然后我有我的onactivityresult,我希望for循环等待,但它只是一遍又一遍地重复使用谷歌麦克风,然后一旦循环完成就停止,永远不会让用户有机会回答
protected override void OnActivityResult(int requestCode,Result resultVal,Intent data)
{
if (requestCode == VOICE)
{
if (resultVal == Result.Ok)
{
var matches = data.GetStringArrayListExtra(RecognizerIntent.ExtraResults);
if (matches.Count != 0)
{
bool saidIt = false;
while (!saidIt)
{
string textInput = textBox.Text + matches[0];
textBox.Text = textInput;
//set alert for executing the task
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Is " + textBox.Text + ", what you said?");
alert.SetPositiveButton("Yes", (senderAlert, args) =>
{
noResponse = false;
saidIt = true;
SetResult(Result.Ok);
//change value write your own set of instructions
//you can also create an event for the same in xamarin
//instead of writing things here
if (textBox.Text == CurrWord)
{
guess(1);
}
else
{
guess(0);
}
});
alert.SetNegativeButton("No", (senderAlert, args) =>
{
//perform your own task for this conditional button click
});
//run the alert in UI thread to display in the screen
RunOnUiThread(() =>
{
alert.Show();
});
}
}
base.OnActivityResult(requestCode, resultVal, data);
}
}
}
答案 0 :(得分:3)
StartActivityForResult不会等待结果,因此您无法在循环中使用它。你必须为第一个单词调用StartActivityForResult,然后当你在OnActivityResult中得到结果时,看看你是否已经完成了所有的单词(使用索引和词典的一些类变量),如果你没有那么为下一个单词调用StartActivityForResult,依此类推,直到你完成。