[英]how to implement back pressed activity in fragment in android
I have develop application which has many fragment activity like home, gallery, songs, other so my issue is when i play audio in songs fragment and then I press back button to get exit from the application but audio playing continuously so I want to code on back press button but I don't know how to work and which method should override like in activity finish() method in on back pressed method 我开发了具有很多片段活动的应用程序,例如家庭,画廊,歌曲等,所以我的问题是当我在歌曲片段中播放音频时,然后按“后退”按钮退出该应用程序,但音频不断播放,因此我想编码后按按钮,但是我不知道如何工作以及应该重载哪个方法,例如在后按方法中的活动finish()方法中
my code 我的代码
*public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_aarti_fragment, container, false);
btnplay=(ImageButton)v.findViewById(R.id.btnplay);
btnstop=(ImageButton)v.findViewById(R.id.btnstop);
seekbar=(SeekBar)v.findViewById(R.id.seekbar);
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
Toast.makeText(getActivity(), "Stop",Toast.LENGTH_LONG).show();
btnplay.setImageResource(R.drawable.ic_action_play);
try
{
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getActivity(),"Aarti Currently not playing",Toast.LENGTH_SHORT).show();
}
}
});
btnplay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.pause();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Pause",Toast.LENGTH_SHORT).show();
finalTime = mp.getDuration();
startTime = mp.getCurrentPosition();
if(oneTimeOnly == 0)
{
seekbar.setMax((int) finalTime);
oneTimeOnly = 1;
}
seekbar.setProgress((int)startTime);
handler.postDelayed(UpdateSongTime,100);
}
else
{ btnplay.setImageResource(R.drawable.ic_action_pause);
mp.start();
Toast.makeText(getActivity(), "Play",Toast.LENGTH_SHORT).show();
finalTime = mp.getDuration();
startTime = mp.getCurrentPosition();
if(oneTimeOnly == 0)
{
seekbar.setMax((int) finalTime);
oneTimeOnly = 1;
}
seekbar.setProgress((int)startTime);
handler.postDelayed(UpdateSongTime,100);
}
}
});
return v;*
} }
Instead of overriding back button etc, you should use fragment lifecycle methods. 而不是覆盖后退按钮等,您应该使用片段生命周期方法。
You can override onStop() method in fragment to release media resource or stop. 您可以覆盖片段中的onStop()方法以释放媒体资源或停止播放。
@Override
public void onStop() {
super.onStop();
mp.release(); // or pause or stop.
Log.i(TAG, "onStop");
}
To control back button, in your activity class 要控制后退按钮,在您的活动课中
@Override
public void onBackPressed() {
// do something, show toast message to confirm or go to another activity
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.