Android应用MP3播放暂停按钮点击切换图标功能实现问询
Got it, let's get that play/pause icon swapping working smoothly! The core idea is to update the button's drawable right after you handle the play/pause logic, based on the current state of your MediaPlayer.
First, make sure you have your play and pause icons ready in the drawable folder (let's say you're using ic_play_circle for play and ic_pause_circle for pause — replace these with your actual icon names).
Here's the modified version of your code with the icon toggle logic added:
// Initialize class-level variables (add these if you haven't already) private MediaPlayer mp; private int length = 0; Button play; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_activity_layout); // Replace with your actual layout ID play = findViewById(R.id.play); // Set initial icon (starts in paused state) play.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_play_circle, 0, 0); // Use this instead if your icon is the button background: // play.setBackgroundResource(R.drawable.ic_play_circle); play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mp != null && mp.isPlaying()) { // Pause the media mp.pause(); length = mp.getCurrentPosition(); // Switch button to show play icon play.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_play_circle, 0, 0); } else { if (mp == null) { // Initialize MediaPlayer if it hasn't been created yet mp = MediaPlayer.create(PunjabiActivity.this, R.raw.japji); } else { // Resume playback from the saved position mp.seekTo(length); } mp.start(); // Switch button to show pause icon play.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_pause_circle, 0, 0); } } }); } // Clean up MediaPlayer to avoid memory leaks @Override protected void onDestroy() { super.onDestroy(); if (mp != null) { mp.release(); mp = null; } }
Quick Tips:
- Icon Placement: Adjust the
setCompoundDrawablesWithIntrinsicBoundsparameters if your icon is on a different side (left/right/top/bottom) of the button text. If you're using the icon as the button's background, replace it withsetBackgroundResource(). - Initial State: We set the play icon first because the media starts paused. If your media auto-plays when the activity launches, swap the initial icon to pause.
- MediaPlayer Lifecycle: The
onDestroymethod ensures we release the MediaPlayer when the activity closes, preventing crashes or battery drain.
This will make the icon toggle instantly every time you tap the button, perfectly matching the current playback state.
内容的提问来源于stack exchange,提问作者Chand Ninder
相关产品推荐
相关产品推荐

