androidandroid-viewpagertext-to-speech

Text-to-Speech in on View Pager


-- How to implement this in viewpager,and speak(convert) text that are particular in page


Solution

  • The easiest way would be to make the tts object static in MainActivity

    Then from your fragments you can call MainActivity.tts.stop() etc.

    It would probably be better to include some helper methods in MainActivity such as:

    public static TextToSpeech getTTS(){
    return tts;
    }
    

    and to avoid null pointers:

    public static boolean isTTSAvailable(){
    return tts != null // && ttsInitialised
    }
    

    Where you would set a static boolean to true if onInit returned SUCCESS.

    MainActivity would continue to handle releasing the tts object in onDestroy etc.

    As a side note, it's always good practice to check out the memory profiler in Android Studio to make sure that holding a static reference to any object such as this has no adverse effects. Do before and after analysis and run the garbage collector manually etc to check you are holding no unwanted references after your Activity has been destroyed. This is very generic advice, but whenever making a code change such as this, it's good to know that there are no side-effects.