OnCompletion mediaPlayer不会更改图像资源

时间:2014-11-06 10:10:17

标签: android android-mediaplayer imagebutton

一旦mediaPlayer播放完音频,我就会尝试更改分配给ImageButton的资源。这是我的代码,但id不起作用:

play.setImageResource(R.drawable.play);
        play.invalidate();

        play.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                play = (ImageButton) v.findViewById(R.id.imagePlay);

                if(isPlaying){  
                        mMediaPlayer.stop();  
                        mMediaPlayer.release();
                        mMediaPlayer = null;
                        play.setImageResource(R.drawable.play);
                        play.invalidate();
                        isPlaying = false;
                }
                else{
                    mMediaPlayer = MediaPlayer.create(context, songs[position]);                
                    mMediaPlayer.start();
                    isPlaying = true;
                    play.setImageResource(R.drawable.stop);
                    play.invalidate();

                    mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

                        public void onCompletion(MediaPlayer mp) {
                            isPlaying = false;

                            play.setImageResource(R.drawable.play);
                            play.invalidate();
                        }
                    });
                }
            }
        });

2 个答案:

答案 0 :(得分:1)

首先尝试请求布局:

public void onCompletion(MediaPlayer mp) {
                            isPlaying = false;

                            play.requestLayout(); //call this
                            play.setImageResource(R.drawable.play);
                            play.invalidate();
                        }

如果仍然无效,请尝试更改此代码

play.setImageResource(R.drawable.play);

致:

play.setImageDrawable(context.getResources().getDrawable(R.drawable.play));

或者如果您仍想使用setImageResource:

int id = getResources().getIdentifier(R.drawable.play, "drawable", getPackageName());
play.setImageResource(id);

答案 1 :(得分:1)

而不是

public void onCompletion(MediaPlayer mp) {
         ...

你应该:

@Override
public void onCompletion(MediaPlayer mp) {
        ...