我看过所有关于这个主题的问题,但无法理解它。它在三星Galaxy S4上进行了测试。这来自我的activity_main.xml。
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/llListe"
android:orientation="vertical"
>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/lstListe"
android:layout_gravity="center"
android:background="#bcffb9" />
</LinearLayout>
这是MainActivity.java。我已经测试了来自speechRecognizer的结果并返回了说出的单词。问题是将此字符串添加到ListView。我已经放弃了,所以请原谅。我做错了什么?
public class MainActivity extends Activity implements View.OnClickListener {
protected static final int REQUEST_OK = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btnSpeek).setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,"en-US");
try {
startActivityForResult(intent,REQUEST_OK);
} catch (Exception e) {
Toast.makeText(this, "Unable to initialize speech engine.", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ListView lv;
ArrayList<String> inputString = new ArrayList<String>();
ArrayAdapter<String> adapter;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_OK && resultCode==RESULT_OK) {
inputString = (data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS));
//Toast.makeText(this,"You said "+inputString.get(0), Toast.LENGTH_SHORT).show();
lv = (ListView) findViewById(R.id.lstListe);
adapter = new ArrayAdapter(this,R.id.lstListe,inputString);
lv.setAdapter(adapter);
}
}
}
答案 0 :(得分:1)
我认为您应该将此行super.onActivityResult(requestCode, resultCode, data);
放在onActivityResult
方法的else条件中,以便在请求代码为REQUEST_OK
时确保您的代码已执行。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ListView lv;
ArrayList<String> inputString = new ArrayList<String>();
ArrayAdapter<String> adapter;
if (requestCode==REQUEST_OK && resultCode==RESULT_OK) {
inputString = (data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS));
//Toast.makeText(this,"You said "+inputString.get(0), Toast.LENGTH_SHORT).show();
lv = (ListView) findViewById(R.id.lstListe);
adapter = new ArrayAdapter(this,R.id.lstListe,inputString);
lv.setAdapter(adapter);
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}