0

I'm working on a project where an ImageView element should only be visible while a MediaPlayer object is playing.

The state of the MediaPlayer can change at any time.

What would be the best way to hook this up? I've considered running a thread in the background, but it seems a bit heavy for such a small thing.

Here's the current code for the thread, and the app runs, but the image doesn't display.

Thread imageRender = new Thread() {
    @Override
    public void run() {
        if (mp.isPlaying() && img.getVisibility() == View.INVISIBLE) {
            img.setVisibility(View.VISIBLE);
        } else if (!mp.isPlaying() && img.getVisibility() == View.VISIBLE) {
            img.setVisibility(View.INVISIBLE);
        }
    }
};
Kona
  • 3
  • 2

1 Answers1

0

You need to handle update the UI on the UI thread. The simple way can fix your problem

    Thread imageRender = new Thread() {
        @Override
        public void run() {
            if (mp.isPlaying() && img.getVisibility() == View.INVISIBLE) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        img.setVisibility(View.VISIBLE);
                    }
                });
            } else if (!mp.isPlaying() && img.getVisibility() == View.VISIBLE) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        img.setVisibility(View.INVISIBLE);
                    }
                });

            }
        }
    };
Liem Vo
  • 5,149
  • 2
  • 18
  • 16