Reputation: 1
I have this code:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
MediaPlayer sound1, sound2;
sound1 = MediaPlayer.create(this, R.raw.cows);
sound2 = MediaPlayer.create(this, R.raw.sheep);
final Button button1 = (Button) findViewById(R.id.Button01);
button1.setOnClickListener(this);
final Button button2 = (Button) findViewById(R.id.Button02);
button1.setOnClickListener(this);
public void onClick(View v) {
switch(v.getId()) {
case R.id.Button01:
sound1.start();
break;
case R.id.Button02:
sound2.start();
break;
}
}
protected void onDestroy() {
sound1.release();
sound2.release();
super.onDestroy();
}
}
I have a warning that says that the button and the view are not correct.
However, I don't understand what's wrong with the above code.
It seems that I need to instantiate the button class and the View class.
But I don't know how to do that.
Upvotes: 0
Views: 277
Reputation: 331
First you have to put `final Button button1 = (Button) findViewById(R.id.Button01); button1.setOnClickListener(this);
final Button button2 = (Button) findViewById(R.id.Button02); button1.setOnClickListener(this); ` in onCreate() method.
Them write (implements OnClickListener after extends Activity )that will ask to implement methods click that
That will automatically create onclick method. in that put you switch code in it.
Hope It Will works and Help you to solve error.
Upvotes: 2
Reputation: 1709
Implement View.onClickListener
and above the ònClick` method you should include the @Override notation
Upvotes: 0
Reputation: 133580
This should be inside a method
sound1 = MediaPlayer.create(this, R.raw.cows);
sound2 = MediaPlayer.create(this, R.raw.sheep);
final Button button1 = (Button) findViewById(R.id.Button01);
button1.setOnClickListener(this);
final Button button2 = (Button) findViewById(R.id.Button02);
button1.setOnClickListener(this); // should be button2
You can initialize your views in onCreate
Button button1,button2;
MediaPlayer sound1,sound2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sound1 = MediaPlayer.create(this, R.raw.cows);
sound2 = MediaPlayer.create(this, R.raw.sheep);
button1 = (Button) findViewById(R.id.Button01);
button1.setOnClickListener(this);
button2 = (Button) findViewById(R.id.Button02);
button2.setOnClickListener(this);
}
Then
public class MainActivity extends Activity implements onClickListener {
Upvotes: 3