tom-james tom-james - 3 months ago 10
Android Question

Why does onClickListener for start, pause, stop buttons only need to be @override once?

I understand how to start, pause & stop a song, but why don't all onClickListener() need an @override?

I'm learning about MediaPlayer & AudioManager at the moment and would like to understand the reason for the layout on MainActivity.java below.

final MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.desiigner_panda);

Button playButton = (Button) findViewById(R.id.Play_Button);
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
Toast.makeText(MainActivity.this, "I'm Done", Toast.LENGTH_SHORT);
}
});
}
});

Button pauseButton = (Button) findViewById(R.id.Pause_Button);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mediaPlayer.pause();
}
});

Button unMuteButton = (Button) findViewById(R.id.Unmute_Button);
unMuteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mediaPlayer.setVolume(1,1);
}
});

Button MuteButton = (Button) findViewById(R.id.Mute_Button);
MuteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mediaPlayer.setVolume(0,0);
}
});
}
}

Answer

No method needs @Override.

@Override is a hint to the compiler, indicating that you think that you are either overriding a method from a superclass or implementing a method from an interface. If you have @Override, and there is a mistake in your method signature (wrong parameters, wrong return type, etc.), the compiler can let you know about it.

You could remove @Override from the one method where it appears in your code listing, and your code would run just fine.

Having @Override is a good idea, to help catch bugs when you are writing your app, but it is not a requirement.

Comments