I want to implement TTS function in fragment in my app, but failed due to not enough understanding between Activity and Fragment.
But found some sources in stackoverflow.com! (Link:http://stackoverflow.com/questions/16866173/text-to-speech-in-fragment)
However, I failed over and over again.. and found the cause.. It was "return view" code in onInit.
Anyhow, finally I succeeded, below is my source.
Fragment.java
public class Q01Fragment extends Fragment implements View.OnClickListener, TextToSpeech.OnInitListener { private TextToSpeech txts; private static final String TAG = "TextToSpeechDemo"; private static final int MY_DATA_CHECK_CODE = 1234; private TextToSpeech tts; //private Button btnSpeak; //private EditText txtText; public static Q01Fragment newInstance() { Q01Fragment fragment = new Q01Fragment(); return fragment; } public Q01Fragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_q01, container, false); Button button = (Button) view.findViewById(R.id.button_Q01); button.setOnClickListener(this); txts = new TextToSpeech(getActivity(), this); // Fire off an intent to check if a TTS engine is installed Intent checkIntent = new Intent(); checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(checkIntent, MY_DATA_CHECK_CODE); return view; } @Override public void onDestroy() { // Don't forget to shutdown! if (txts != null) { txts.stop(); txts.shutdown(); } super.onDestroy(); } private void speakOut() { String text = "This is New code"; txts.speak(text, TextToSpeech.QUEUE_FLUSH, null); }
@Override public void onClick(View v) { switch (v.getId()) { case R.id.button_Q01: //Toast.makeText(getActivity(), "One Fragment", Toast.LENGTH_SHORT).show(); speakOut(); break; } } @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int result = txts.setLanguage(Locale.US); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("TTS", "Language is not supported"); } else { } } else { Log.e("TTS", "Initilization Failed"); } } } |
'Android Programming' 카테고리의 다른 글
안드로이드 앱 개발 머신 맥북프로 입양 (0) | 2015.09.14 |
---|---|
Audio recorder (0) | 2015.06.22 |
안드로이드에서 엑셀파일 읽기 - 삽질 (0) | 2015.06.08 |
엑셀 파일의 내용을 안드로이드 DB 파일에 저장하기 (외장메모리) (0) | 2015.06.04 |
이제는 안드로이드 스튜디오가 대세? (0) | 2015.05.28 |