Set ToggleButton to play default sound when pressed?

My android apps have a regular button:

<Button android:id="@+id/allOnButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="130dp" android:text="@string/sensor_management_all_on" /> 

And the switch button:

 <ToggleButton android:id="@+id/accelerometerToggleButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:textOff="off" android:textOn="on" /> 

When the button is pressed, a pleasant β€œclick” sound is played, which gives good feedback to the user that the button has been pressed.

How to set click sound for ToggleButton?

+6
source share
2 answers

To hear the click sound, you need to install clickListener.

So, set the dummy onClickListener to ToggleButton , it should reproduce the sound effect.

+3
source
  toggleButton = (ToggleButton)findViewById(R.id.sound); final MediaPlayer mp = MediaPlayer.create(this, R.raw.theme); if(toggleButton.isChecked()) mp.start(); toggleButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!toggleButton.isChecked()){ mp.pause(); } else { mp.start(); mp.isLooping(); } } }); 
0
source

Source: https://habr.com/ru/post/925511/


All Articles