Android自定义点击带声音的控件TextViewButtonListView

android控件在setonclick方法时,在点击时,就会触发performClick()方法,我们可以在自定义控件实现此方法,调用一个发声音的方法,即可以实现点击控件发出声音。

自定义控件

这里只写一个Imageview自定义,其他的所有控件几乎都是一样,实现performClick()即可。

public class MyImageView extends ImageView {

    public MyImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyImageView(Context context) {
        super(context);
    }

    @Override
    public boolean performClick() {
        //调用发声方法
        BaseApplication.playClickVoice(getContext());
        return super.performClick();
    }
}

我在Application里面自定义了一个发声方法,在网上百度了一个音频文件,把音频文件放在raw文件下

    public static MediaPlayer mp;  //音频播放
    public static void playClickVoice(Context context){
        if (true) {
            try {
                if (mp == null) {
                    mp = new MediaPlayer(); 
                }   
                mp.reset();
                AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.button_click_voice);
                if (afd == null)  return; 
                mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                afd.close();

                mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mp.prepare();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mp.start();
        } 
    }

本文参考来源:
[1]https://blog.csdn.net/u011747761/article/details/46791107

猜你喜欢

转载自blog.csdn.net/wq6ylg08/article/details/90021811