单击时自定义按钮类有声音

时间:2017-03-08 08:26:34

标签: android button

在我的应用程序中,我希望在单击按钮时设置声音并且我使用了媒体播放器,它完成了。但是当我在很多活动中有很多按钮时,它非常复杂,所以我想创建一个按钮类,它可以扩展按钮并在事件点击按钮中添加声音。

有可能吗?怎么做呢?

1 个答案:

答案 0 :(得分:0)

试试这个,

        import android.content.Context;
        import android.media.MediaPlayer;
        import android.util.AttributeSet;
        import android.util.Log;
        import android.view.View;
        import android.widget.Button;

        public class CustomButton extends Button implements View.OnClickListener {

            Context mContext;
            public CustomButtonTest(Context context, AttributeSet attrs, int defStyle) {
                super(context, attrs, defStyle);
                mContext=context;
                init();
            }

            public CustomButtonTest(Context context, AttributeSet attrs) {
                super(context, attrs);
                mContext=context;
                init();
            }

            public CustomButtonTest(Context context) {
                super(context);
                mContext=context;
                init();
            }

            private void init(){
                setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
                // Do something
                Log.d("TAG","@@@@@@@@@@ onClick");
                MediaPlayer mediaPlayer = new MediaPlayer();
                mediaPlayer = mediaPlayer.create(mContext, R.raw.xoay_touch_sound); mediaPlayer.start();


               /*

                OR you can try below code also
                */

                /*Log.d("TAG","@@@@@@@@@@ onClick");
                int MAX_SOUND_POOL_STREAMS = 4;


                SoundPool soundPool = new SoundPool(MAX_SOUND_POOL_STREAMS,
                        AudioManager.STREAM_MUSIC, 100);
                int mySoundId = soundPool.load(mContext,
                        R.raw.xoay_touch_sound, 1);

                AudioManager audioManager = (AudioManager) mContext.getSystemService(mContext.AUDIO_SERVICE);
                float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                float volume = actualVolume / maxVolume;
                soundPool.play(mySoundId, volume, volume, 1, 0, 1f);*/
            }

        }

XML

    <yourPakageName.CustomButton 
        android:id="@+id/test"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />