public class AudioRecorderButton extends Button {
private static final int DISTANCE_Y_CANCEL = 50;
/** 按钮的三种状态 */
private static final int STATE_NORMAL = 1;// 正常状态
private static final int STATE_RECRODING = 2;// 录音状态
private static final int STATE_WANT_CANEL = 3;// 取消状态
private int mCurSTATE = STATE_NORMAL;// 变量 记录当前按钮的状态 默认下为正常状态
private boolean isRecording = false;// 如果是已经开始录音
private DialogManager mDialogManager;
public AudioRecorderButton(Context context, AttributeSet attrs) {
super(context, attrs);
mDialogManager = new DialogManager(getContext());
setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
mDialogManager.showRecordingDialog();
isRecording = true;
return false;
}
});
}
public AudioRecorderButton(Context context) {
this(context,null);
}
/**
* 重写按钮Button 的 onTouchEvent方法
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
int x = (int) event.getX();
int y = (int) event.getY();
switch (action) {
case MotionEvent.ACTION_DOWN:// 按钮按下
Log.e("AudioRecorderButton", "已经按下-------x="+x+"y="+y);
changeState(STATE_RECRODING);
break;
case MotionEvent.ACTION_MOVE:// 按钮移动时
if (isRecording) {
// 根据用户移动的 xy的坐标判断用户是否想要取消当次语音发送
Log.e("AudioRecorderButton", "x="+x+"y="+y);
if (wantCancel(x, y)) {
changeState(STATE_WANT_CANEL);
} else {
changeState(STATE_RECRODING);
}
} else {// 提示录音时间太短?
}
break;
case MotionEvent.ACTION_UP:// 按钮松开时
Log.e("AudioRecorderButton", "已经松开-------x="+x+"y="+y);
if (mCurSTATE == STATE_RECRODING) {// 是录音
mDialogManager.dimissDialog();
} else if (mCurSTATE == STATE_WANT_CANEL) {// 想取消
mDialogManager.dimissDialog();
}
reset();
break;
}
return true;
}
/**
* 恢复状态和标志位
*/
private void reset() {
isRecording = false;
changeState(STATE_NORMAL);
}
private boolean wantCancel(int x, int y) {
if (x < 0 || x > this.getWidth()) {//手指滑动已经超出按钮
return true;
}
if (y < -DISTANCE_Y_CANCEL || y > DISTANCE_Y_CANCEL + getHeight()) {
return true;
}
return false;
}
private void changeState(int CURRENT_STATE) {
if (CURRENT_STATE != mCurSTATE) {// 当前传入状态不等于当前默认状态
mCurSTATE = CURRENT_STATE;
switch (mCurSTATE) {
case STATE_NORMAL:
setBackgroundResource(R.drawable.but_recorder_normal);
setText(R.string.str_voice_normal);
break;
case STATE_RECRODING:
setBackgroundResource(R.drawable.but_recording);
setText(R.string.str_voice_recording);
if (isRecording) {
mDialogManager.recording();
}
break;
case STATE_WANT_CANEL:
setBackgroundResource(R.drawable.but_recording);
setText(R.string.str_voice_want_cancel);
mDialogManager.wantToCancel();
break;}}}}