如何正确停止媒体播放器

时间:2019-03-09 13:51:42

标签: android android-mediaplayer

当用户单击“后退”按钮时,如何通过pageradapter停止媒体播放器的片段活动?

每次单击后退按钮时,音频仍在播放。

package com.androidbasedcollectionofstories;

import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class BRUSH1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) 
{
        // TODO Auto-generated method stub
        View view =inflater.inflate(R.layout.brushing1,container,false);
        ImageView imageview = (ImageView) view.findViewById (R.id.imageView1);
        if(imageview == null) throw new AssertionError();
        imageview.setBackgroundResource(R.drawable.animbrushing1);
        AnimationDrawable anim = (AnimationDrawable)imageview.getBackground();
        anim.start();

        final MediaPlayer sound=MediaPlayer.create(getActivity(), R.raw.brushingtitle);
        sound.start();
        return view;
    }

}

1 个答案:

答案 0 :(得分:0)

如果需要停止媒体播放器,则可以使用onDestroyView方法停止。

public class BRUSH1 extends Fragment {

    MediaPlayer sound;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view =inflater.inflate(R.layout.brushing1,container,false);
        ImageView imageview = (ImageView) view.findViewById (R.id.imageView1);
        if(imageview == null) throw new AssertionError();
        imageview.setBackgroundResource(R.drawable.animbrushing1);
        AnimationDrawable anim = (AnimationDrawable)imageview.getBackground();
        anim.start();

        sound = MediaPlayer.create(getActivity(), R.raw.brushingtitle);
        sound.start();
        return view;
    }

    @Override
    public void onDestroyView() {
        if (sound != null) {
            sound.stop();
            sound.release();
        }
        super.onDestroyView();
    }

}