我在Android开发中随处可见音乐。我看过API,但我不明白。这是我的代码:
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(Main.this, R.raw.track1);
mp.start();
}
});
我如何更改它以便当我再次按下相同按钮时它会停止它?
答案 0 :(得分:1)
package com.my.testing;
import android.R;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class TestAndActivity extends Activity {
public MediaPlayer mp = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mp == null) {
mp = MediaPlayer.create(TestAndActivity.this, R.raw.track1);
mp.start();
} else {
mp.stop();
mp = null;
}
}
});
}
}
答案 1 :(得分:0)
为了好玩,你可以在你的布局中的同一个地方定义两个相同的按钮并制作这样的技巧......
<ImageView
android:id="@+id/media_player12"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="@drawable/media_player" />
<ImageView
android:id="@+id/mute12"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:visibility="gone"
android:clickable="false"
android:src="@drawable/mute" />
和代码......
final ImageView s_on12 = (ImageView) findViewById(R.id.media_player12);
s_on12.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.release();
MediaPlayer mp = MediaPlayer.create(Main.this, R.raw.track1);
mp.start();
final ImageView s_off12 = (ImageView) findViewById(R.id.mute12);
s_on12.setVisibility(View.GONE);
s_on12.setClickable(false);
s_off12.setVisibility(1);
s_off12.setClickable(true);
s_off12.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.stop();
s_on12.setVisibility(1);
s_on12.setClickable(true);
s_off12.setVisibility(View.GONE);
s_off12.setClickable(false);
}
});
}
});