Text To Speech In Fragment
Solution 1:
As I said in my comment: using this while in a Fragment refers to that Fragment's instance. Fragments aren't Contexts, hence the compile time error.
To make a new TextToSpeech Object, you should use:
txts = new TextToSpeech(getActivity(), this);Activities extend Context, so that should fix this compile-time error.
Another potential problem: for the Buttons, TextViews, etc that you are setting up onCreateView() you should be using view.findViewById() instead of getView().findViewById() (but only for the Views you're setting up in onCreateView(). The rest of the getView() calls should be fine).
It's one less method call, and getView() probably returns null until onCreateView() returns the inflated View.
Lastly, onCreateView() needs to return a View, so just before its closing brace, add:
return view;
The method with appropriate changes:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Viewview= inflater.inflate(R.layout.fragment_1,
container, false);
ButtonbtnAdd= (Button) view.findViewById(R.id.button1);
btnAdd.setOnClickListener(this);
btnAdd.setEnabled(false);
TextViewtxt= (TextView) view.findViewById(R.id.textView1);
txt.setText("OnCreate");
// Fire off an intent to check if a TTS engine is installedIntentcheckIntent=newIntent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
return view;
}
Solution 2:
You can initialize the class inside of TextToSpeech.OnInitListener() method.
// variable declaration
TextToSpeech tts;
// TextToSpeech initialization, must go within the onCreateView method
tts = newTextToSpeech(getActivity(), newTextToSpeech.OnInitListener() {
@OverridepublicvoidonInit(int i) {
if (i == TextToSpeech.SUCCESS) {
intresult= tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Lenguage not supported");
}
} else {
Log.e("TTS", "Initialization failed");
}
}
});
// method call@OverridepublicvoidonClick(View v) {
speak();
}
privatevoidspeak() {
tts.speak("Text to Speech Test", TextToSpeech.QUEUE_ADD, null);
}
@OverridepublicvoidonDestroyView() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroyView();
}
taken from: Text to Speech Youtube Tutorial
Post a Comment for "Text To Speech In Fragment"