I'm trying to do some simple apps like click button, play sound. In my last App I did it all with switch cases but I realized that if I have a lot of codes I have to write a lot of code for each button one case. Now I am trying to save my buttons and my sounds into Arrays and looping them in a double for.
I also did some context menu which is working fine. But my problem now is the playing the sounds. Actually it plays the sound2 for both buttons. It should play for button1 -> sound1 and for button2 -> sound2
Can somebody find my Problem here?
public class MainActivity extends AppCompatActivity {
MediaPlayer MainMedia;
public int [] buttonsas = {R.id.button1, R.id.button2};
public int [] sounds = {R.raw.sound1, R.raw.sound2};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i=0; i<buttonsas.length; i++) {
Button contextMenuButton = (Button) findViewById(buttonsas[i]) ;
registerForContextMenu(contextMenuButton);
}
MainMedia = MediaPlayer.create(this, R.raw.sound1);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.item_option1:
case R.id.item_option2:
Toast.makeText(this, item.toString(), Toast.LENGTH_LONG).show();
break;
case R.id.item_option3:
Toast.makeText(this, item.toString(), Toast.LENGTH_LONG).show();
break;
}
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.main_menu, menu);
}
public void MainMedia (View view) {
for (int i=0; i<buttonsas.length; i++) {
for (int j=0; j<sounds.length; j++) {
MainMedia.release();
MainMedia = MediaPlayer.create(MainActivity.this, sounds[j]);
MainMedia.start();
}
}
}
}