我的活动中有一个滑块片段。我正在尝试在片段可见时播放声音,并在用户滑动到另一个片段时停止媒体播放器。这是我的代码。我已经尝试为片段实现onHiddenChanged方法,但声音一直在播放。
public class WorkoutBuddyViewFragment extends Fragment {
MediaPlayer mp;
public WorkoutBuddyViewFragment() {
}
ImageButton play;
TextView display;
// BPPVComment#7: For now, this is a placeholder screen.
// override to provide sensor assisted exercise session
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View pageView = null;
pageView = inflater.inflate(R.layout.workout_buddy_dummy, container, false);
play = (ImageButton) pageView.findViewById(R.id.playButton);
display = (TextView) pageView.findViewById(R.id.textForWOB);
mp = MediaPlayer.create(getActivity(), R.raw.welcome);
try
{
mp.start();
}
catch (NullPointerException e)
{
display.setText("Null Pointer Exception");
}
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent startExercise = new Intent("android.intent.action.exercise");
startActivity(startExercise);
}
});
return pageView;
}
@Override
public void onHiddenChanged(boolean hidden) {
// TODO Auto-generated method stub
super.onHiddenChanged(hidden);
try
{
mp.stop();
}
catch(NullPointerException e)
{
e.printStackTrace();
}
}
}
答案 0 :(得分:3)
我会尝试这个, setUserVisibleHint 方法。
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
// Make sure that we are currently visible
if (this.isVisible()) {
// If we are becoming invisible, then...
if (!isVisibleToUser) {
mp.stop();
}
else {
// do what you like
}
}
}
答案 1 :(得分:0)
public class VideoFragment extends Fragment{..............
private VideoView video;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (video == null) {
return;
}
if (isVisibleToUser) {
video.start();
}
else {
video.stopPlayback();
}
}