2015-05-19 113 views
0

请让我遇到问题,让仿真器在我的代码上工作。我有下面的代码,我希望能够播放声音,当我点击我在模拟器上创建的按钮,但是每当我运行代码时,模拟器不会弹出,而是弹出媒体播放器并播放声音它自己的。请帮忙。有什么我做错了吗?谢谢你的帮助。让仿真器运行

下面是我的代码

公共类声音扩展ActionBarActivity {

MediaPlayer Sound; 
private static Button btnsound; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_sound); 
    Sound = MediaPlayer.create(this, R.raw.coins); 
    playsound(); 
} 

public void playSound (View view) { 
    Sound.start(); 
} 

public void playsound(){ 
    btnsound=(Button) findViewById(R.id.button_sound); 

    btnsound.setOnClickListener(
      new View.OnClickListener(){ 
       @Override 
      public void onClick (View v){ 

        Sound.start(); 

       } 
}); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_sound, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

}

的activity.xml

<Button 
    android:layout_width="175dp" 
    android:layout_height="wrap_content" 
    android:text="@string/btnsound" 
    android:onClick="playSound" 
    android:id="@+id/button_sound" 
    android:layout_gravity="center_horizontal" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 

    android:layout_marginTop="154dp" /> 

回答

0

确保声音播放在它自己的,你有内部onCreate的方法playsound()一个电话,删除该行并调用按钮监听器内部这种方法,使其保持这样的:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_sound); 
    Sound = MediaPlayer.create(this, R.raw.coins); 
    btnsound = (Button) findViewById(R.id.button_sound); 

    btnsound.setOnClickListener(
     new View.OnClickListener(){ 
      @Override 
     public void onClick (View v){ 
       playSound(); 
      } 
    }); 
} 
public void playSound() { 
    Sound.start(); 
} 

你声明和功能有点混乱,小心。

+0

好的。非常感谢。它确实有帮助。我正在逐渐学习。另外,如果我想要有多个声音,我应该为每个声音使用不同的方法,或者我应该做的最好的事情是什么。 – Shade01

+0

这是一个好主意,在你的情况下,我可能会做同样的 – codecharles

+0

谢谢。它终于按照它应该的方式工作。 – Shade01