我有一个按钮,我想要三个功能 在第一次点击它开始录制声音。在第二次点击它将停止第三次点击它显示三个选项(播放声音,录制新的,删除声音)我该如何实现此操作 帮助
k=(Button)findViewById(R.id.button1);
k.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
答案 0 :(得分:3)
您需要设置一个类级别变量并确定发生了什么点击。这种方法的难点在于定义何时重置值。
private int _clicks = 0;
k = (Button)findViewById(R.id.button1);
k.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int count = ++_clicks;
if(count == 1)
//do whatever
if(count == 2)
//do whatever
if(count == 3)
//do whatever
}
});
更好的方法是简单地将多个处理程序分配给多个按钮并执行按钮所需的操作。这将允许您定义1:1关系,并使您的代码更易于管理。
编辑:要录制声音,网络上有plenty of examples。
public class AudioRecorder {
final MediaRecorder recorder = new MediaRecorder();
final String path;
/**
* Creates a new audio recording at the given path (relative to root of SD card).
*/
public AudioRecorder(String path) {
this.path = sanitizePath(path);
}
private String sanitizePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
if (!path.contains(".")) {
path += ".3gp";
}
return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
}
/**
* Starts a new recording.
*/
public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted. It is " + state + ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
}
/**
* Stops a recording that has been previously started.
*/
public void stop() throws IOException {
recorder.stop();
recorder.release();
}
}
答案 1 :(得分:1)
另一种方法是拥有三个不同的onClickListeners。看看这段代码:
在你的onCreate:
...
button.setOnClickListener(playListener);
...
在您的活动中的任何位置为play()
,stop()
和showOption()
创建方法,并且:
OnClickListener playListener = new OnClickListener() {
@Override
public void onClick(View v) {
play();
v.setOnClickListener(stopListener);
}
};
OnClickListener stopListener = new OnClickListener() {
@Override
public void onClick(View v) {
stop();
v.setOnClickListener(showOptionListener);
}
};
OnClickListener showOptionListener = new OnClickListener() {
@Override
public void onClick(View v) {
showOption();
}
};