androidmultithreadingtext-to-speechonutterancecompleted

Android: Only the original thread that created a view hierarchy can touch its views


I am getting error "android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views" when I call listenButton.setAlpha((float)1) in the code below. I understand why, but how can I then modify a button when I receive the onDone event?

public class MainActivity extends ActionBarActivity implements TextToSpeech.OnInitListener {
    [...]
    @Override
    // OnInitListener method to receive the TTS engine status
    public void onInit(int status) {
       if (status == TextToSpeech.SUCCESS) {
         ttsOK = true;
         tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
                @Override
                public void onDone(String utteranceId) {
                    Button listenButton = (Button) findViewById(R.id.listentts);
                    listenButton.setAlpha((float)1);
                    listenButton.setClickable(true);
                }

                @Override
                public void onError(String utteranceId) {
                    Log.d("MainActivity", "Progress on Error " + utteranceId);
                }

                @Override
                public void onStart(String utteranceId) {
                    Log.d("MainActivity", "Progress on Start " + utteranceId);
                }
            });
       }
       else {
         ttsOK = false;
       }
    }
    [...]
}

Solution

  • Try this:

    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            Button listenButton = (Button) findViewById(R.id.listentts);
            listenButton.setAlpha((float)1);
            listenButton.setClickable(true);
        }
    });