How to Add Sound on the Toggle button?

巧了我就是萌 提交于 2019-12-11 08:28:16

问题


I implement a Toggle Botton on Activity. I wanted to add Sound (on & off) to that button but I am not able to add sound on it.

This is the code I wrote.

public class SoundLayout extends Activity implements OnClickListener
{
Button soundBttnOn;
private String _showText;


@Override

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sound_layout);

/** Fetched from the MAIN ACTIVITY */
Bundle bundle = getIntent().getExtras();
if(bundle!=null){
    _showText = bundle.getString("button_click");
}
Log.i("btnClick","button clicked is :"+_showText);
soundBttnOn = (Button) findViewById(R.id.togglebutton);
soundBttnOn.setOnClickListener(this);
}


@Override

public void onClick(View view) {
// TODO Auto-generated method stub
/** make a refernce to store the intent when the view has been clicked*/
Intent intent;  
/** Make cases according to the number of buttons you have in screen
 * In this case, I've added one.*/
switch(view.getId()){

case R.id.togglebutton :
    Log.i("btnClick","Result button is clicked whose id is :"+view.getId());
    /** Intent should be fired from this activity to the other activity*/
    intent = new Intent(SoundLayout.this, Main.class);

    /** Start the intent
     * startActivity(intent);
    this.finish();*/

    break;
}
}

}

Here I tried to add Sound on toggle button, but I am not able to add sound function on it. So when I click on 'sound on', it gets activated and when I click on 'sound off', it gets deactivated.


回答1:


You can make use of setOnCheckedChangeListener of toggle button.In this u get a paramater indicating if the button is in on or off state.Based on it u can play hte required sound using media player.

ToggleButton tb = (ToggleButton) findViewById(R.id.toggleButton);
    tb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked)
                System.out.println("ischecked>>>>>>>>>>>>>>>>>>>>>>>>>.");
            else
                System.out.println("not checked>>>>>>>>>>>>>>>>>>>>>>>>>.");

        }
    });



回答2:


Just place the sound file in /res/raw (after creating the folder) and then use MediaPlayer to init, start and then stop playing the sound.

MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile1); mp.start();

And then you get all the start/stop/reset/pause/release methods from mp.



来源:https://stackoverflow.com/questions/18144522/how-to-add-sound-on-the-toggle-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!