我正在开发应用程序,我正在尝试将语音识别添加到片段中,以便用户可以选择从左向右滚动页面并单击按钮并使用语音识别。但问题是:当我从Fragment扩展时,在onActivityResult中我无法初始化TextView和RESULT_OK。当我从FragmentActivity扩展时,它是onCreateView的下划线。
我应该使用哪个范围来获得我想要的结果?
public class Fragment_1 extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_1_fragment_1, container, false);
ImageButton button1 = (ImageButton)v.findViewById(R.id.voiceRecognition1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "You may speak!");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
startActivityForResult(intent, 1);
}
});
final TextView frag1 = (TextView) v.findViewById(R.id.frag_1_frag_1);
final TextView frag1ru = (TextView) v.findViewById(R.id.frag_1_frag_1_ru);
frag1ru.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (frag1.getVisibility() == View.INVISIBLE) {
frag1.setVisibility(View.VISIBLE);
} else {
frag1.setVisibility(View.INVISIBLE);
}
}
});
return v;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {//RESULT_OK become red
ArrayList<String> results;
results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
TextView speechText = (TextView)findViewById(R.id.textView1);//findViewByID become red
String str="";
for(int i=0;i<results.size();i++){
str+= results.get(i);
}
if (str.equals("five")) {
speechText.setText(str);
}else{
speechText.setText("It's not: " + str);
}
}
}
}