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

603 Views Asked by At

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;
       }
    }
    [...]
}
2

There are 2 best solutions below

0
On BEST ANSWER

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);
    }
});
0
On

Every View has a Handler associated with it, so there's no need to create a new one.

final View v = findViewById(R.id.listentts); // could be a class member
v.getHandler().post(new Runnable() {
    @Override
    public void run() {
        v.setAlpha(1.0f);
        v.setClickable(true);
    }
});