gpt4 book ai didi

android - 当 fragment 不可见时如何停止媒体播放器的声音?

转载 作者:行者123 更新时间:2023-12-05 00:17:37 25 4
gpt4 key购买 nike

我的 Activity 中有一个 slider fragment 。我试图在 fragment 可见时播放声音,并在用户滑动到另一个 fragment 时停止媒体播放器。这是我的代码。我尝试为 fragment 实现 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();
}
}

}

最佳答案

我会尝试这个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
}
}
}

关于android - 当 fragment 不可见时如何停止媒体播放器的声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22310108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com