Как правильно остановить медиаплеер - PullRequest
0 голосов
/ 09 марта 2019

Как остановить медиапроигрыватель во фрагменте с помощью 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 голосов
/ 10 марта 2019

Если вам нужно остановить медиаплеер, то вы можете остановиться методом 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();
    }

}
...