我正在尝试将背景音乐添加到我的应用程序中。我想要的只是在按下时应该播放声音,btnoptn
Button
并且它的文本会转换为“音乐关闭”。音乐应继续播放,Activity
直到返回设置页面并Button
再次按下相同的按钮。音乐随即停止,Button
文本变为“music on”。
到目前为止,这是我的代码:
package hello.english;
import hello.english.R;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.media.MediaPlayer;
import android.os.Bundle;
public class welcome extends Activity implements OnClickListener{
private Button btnoptn;
private Button btnmenu;
public static MediaPlayer mp2;
private void btnoptn(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button testButton = (Button) findViewById(R.id.btnoptn);
testButton.setTag(1);
testButton.setText("Musik Of");
mp2=MediaPlayer.create(this, R.raw.guitar_music);
mp2.start();
mp2.setLooping(true);
testButton.setOnClickListener( new View.OnClickListener() {
public void onClick (View v) {
final int status =(Integer) v.getTag();
if(status == 1) {
mp2.start();
mp2.setLooping(true);
testButton.setText("Musik Of");
v.setTag(0); //pause
} else {
mp2.pause();
testButton.setText("Musik On");
v.setTag(1);
} //pause
}
});
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
btnoptn=(Button)findViewById(R.id.btnoptn);
btnmenu=(Button)findViewById(R.id.btnmenu);
btnoptn.setOnClickListener( new View.OnClickListener() {
public void onClick(View view) {
btnoptn(null);
}
});
btnmenu.setOnClickListener( new View.OnClickListener() {
public void onClick(View view2) {
btnmenu();
}
});
}
protected void btnmenu() {
try {
Intent btnmenu= new Intent (this, menuenglish.class);
startActivity(btnmenu);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onStart() {
super.onStart();
btnoptn.setTag(0);
}
public void onClick(View view2) {
// TODO Auto-generated method stub
}
}