我有一个带有侧面板的平板电脑视图和右侧的主要片段。问题是我有一个MediaPlayer即使有人切换到另一个片段也继续播放,这意味着当用户返回片段时,它会导致暂停按钮崩溃。一旦用户按下另一个片段,它将如何制作它,它会停止/销毁MediaPlayer?
public class Fragment_7 extends Fragment {
private MediaPlayer mp;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_7, null);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
GridView gridView = (GridView)getView().findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(getActivity()));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
stopPlaying();
mp = MediaPlayer.create(getActivity(), R.raw.sound01);
mp.start();
// This will make sound
break;
case 1:
stopPlaying();
mp = MediaPlayer.create(getActivity(), R.raw.sound02);
mp.start();
break;
case 2:
stopPlaying();
mp = MediaPlayer.create(getActivity(), R.raw.sound03);
mp.start();
break;
case 3:
stopPlaying();
mp = MediaPlayer.create(getActivity(), R.raw.sound04);
mp.start();
break;
case 4:
stopPlaying();
mp = MediaPlayer.create(getActivity(), R.raw.sound05);
mp.start();
break;
case 5:
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store"));
startActivity(i);
break;
}
}
});
FloatingActionButton fab = (FloatingActionButton) getView().findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mp.isPlaying()) {
mp.pause();
mp.seekTo(0);
}
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}}}