Android仿微信发送语音消息动态提示,支持上滑取消发送
com.example.voicemessage;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AudioSendActivity extends AppCompatActivity {
private Button btnRecord;
private TextView txtPrompt;
private boolean isRecording = false;
private float startY;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_send);
btnRecord = findViewById(R.id.btn_record);
txtPrompt = findViewById(R.id.txt_prompt);
btnRecord.setOnTouchListener(new View.OnTouchListener() {
@Override public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startRecording(event);
return true;
case MotionEvent.ACTION_MOVE:
if (isRecording) {
cancelRecording(event);
}
return true;
case MotionEvent.ACTION_UP:
if (isRecording) {
stopRecording();
} else {
Toast.makeText(AudioSendActivity.this, "Hold and speak to record", Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
}
});
}
private void startRecording(MotionEvent event) {
isRecording = true;
startY = event.getY();
txtPrompt.setText("Slide up to cancel");
// Start recording audio // Code for starting audio recording goes here }
private void cancelRecording(MotionEvent event) {
float currentY = event.getY();
if (startY - currentY >100) {
isRecording = false;
txtPrompt.setText("Hold and speak to record");
// Cancel recording and discard audio // Code for cancelling recording goes here }
}
private void stopRecording() {
isRecording = false;
txtPrompt.setText("Hold and speak to record");
// Stop recording and send audio // Code for stopping recording and sending audio goes here }
}
在上面的代码中,我们首先获取了"录音"按钮和"提示文字"的实例对象,并为"录音"按钮设置了触摸事件监听器。在触摸事件监听器中,根据手指的动作分别执行开始录音、取消录音和结束录音的操作。
在startRecording()方法中,我们设置isRecording标志为true,并记录下手指按下时的Y坐标。同时修改提示文字为"上滑取消发送",并开始录音。在cancelRecording()方法中,根据手指移动的距离判断是否取消录音。如果手指向上移动的距离超过100像素,我们将isRecording标志设置为false,恢复提示文字为"按住说话发送",并取消录音。在stopRecording()方法中,我们将isRecording标志设置为false,恢复提示文字为"按住说话发送",并结束录音并发送语音消息。
以上就是Android仿微信发送语音消息动态提示,支持上滑取消发送的实现。整体实现思路比较简单,使用触摸事件监听器来监听用户的手势操作,根据用户手指的动作来执行不同的录音操作。同时,在UI上显示相应的提示文字,让用户能够清晰地了解当前的录音状态。这样的实现可以提高用户体验,让用户在发送语音消息时能够更加方便和自然。