我試圖做一些簡單的應用程序,如點擊按鈕,播放聲音。 在我的最後一個應用程序中,我用開關盒完成了所有工作,但是我意識到如果我有很多代碼,我必須爲每個按鈕編寫很多代碼。 現在我試圖將按鈕和聲音保存到數組中,並將它們循環放入雙精度數組中。陣環Android Studio中
我還做了哪些工作正常一些上下文菜單。但現在我的問題是播放聲音。實際上它會播放兩個按鈕的聲音2。 > Sound1例子和BUTTON2 - - 它應該爲Button1發揮> SOUND2
有人可以在這裏找到我的問題?
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();
}
}
}
}
你爲什麼不創建一個方法,並通過與聽衆的onclick聲音文件路徑,以便您的代碼會更乾淨? – madroid
你好,因爲我對Java有點新鮮。你有一點教程嗎? – ExiizZ