Reputation: 353
I am trying to be able to push button 2 without pushing button 1 first to get it to play the sound. This is my code. So if I push button 2 no sound plays until I push button 1
@Override
protected void onCreate(Bundle LiamIsTheBest) {
// TODO Auto-generated method stub
super.onCreate(LiamIsTheBest);
setContentView(R.layout.liam);
Button boton = (Button) findViewById(R.id.button1);
boton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { // onClick Method
// Your Onclick Action Here
MediaPlayer mp = MediaPlayer.create( MainActivity.this, R.raw.eat);
mp.start();
Button play = (Button) findViewById(R.id.button2);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.play);
mp.start();
}
});
}
});
}
};
Xml
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="I want to eat" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="I want to play" />
<
Upvotes: 0
Views: 207
Reputation: 16825
Use this
@Override
protected void onCreate(Bundle LiamIsTheBest) {
super.onCreate(LiamIsTheBest);
setContentView(R.layout.liam);
Button boton = (Button) findViewById(R.id.button1);
boton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create( MainActivity.this, R.raw.eat);
mp.start();
}
});
Button play = (Button) findViewById(R.id.button2);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.play);
mp.start();
}
});
}
Upvotes: 2
Reputation: 18863
Button boton = (Button) findViewById(R.id.button1);
Button play = (Button) findViewById(R.id.button2);
boton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { // onClick Method
// Your Onclick Action Here
MediaPlayer mp = MediaPlayer.create(MainActivity.this,
R.raw.eat);
mp.start();
}
});
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(MainActivity.this,
R.raw.play);
mp.start();
}
});
You are declaring your play button and setting the OnClickListener
within the onClick()
of your first button. You should declare them first and set the OnClickListener
separately;
Tip: If you are using eclipse, ctrl+shift+f to format your code so you know where your brackets should be.
Upvotes: 1