请耐心等待,这实际上是我第一次使用Android Studio和Stackoverflow。我想要做的是一个音乐播放器,有2个活动。在用户轻敲播放按钮的第二个活动中,播放音乐。如果用户后退,音乐将停止播放并返回第一个活动。不知何故,背压不起作用。它变灰了,它告诉我方法从未使用过。
package com.radiantminds.radiantminds;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class player1 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mozardpianosonata); //create mediaplayer with song
ImageButton yButton = (ImageButton) findViewById(R.id.imageButton5);
yButton.setOnClickListener(new View.OnClickListener() {
public void onBackPressed(){ //this is not working
if(mp.isPlaying())
{
mp.stop(); // stop music on backpress
}
}
@Override
public void onClick(View view) { //play music on click
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
}
});
}
}
答案 0 :(得分:1)
您必须将其置于public static int numDaysBetween(final Calendar c, final long fromTime, final long toTime) {
int result = 0;
if (toTime <= fromTime) return result;
c.setTimeInMillis(toTime);
final int toYear = c.get(Calendar.YEAR);
result += c.get(Calendar.DAY_OF_YEAR);
c.setTimeInMillis(fromTime);
result -= c.get(Calendar.DAY_OF_YEAR);
while (c.get(Calendar.YEAR) < toYear) {
result += c.getActualMaximum(Calendar.DAY_OF_YEAR);
c.add(Calendar.YEAR, 1);
}
return result;
}
上,不要忘记致电Activity
@Override
问题是您必须将@Override
public void onBackPressed()
{
super.onBackPressed(); //if you want to do something new remove this line
}
放在外面,如下所示:
onBackPressedMethod()
答案 1 :(得分:0)
确保@override位于方法之上,并且您不会将方法声明两次。 另一种选择是:
onKeyDown()
或添加:
super.onBackPressed();
在onBackPressed方法中(尽管我并不是真的建议)