[英]How can i react from Dialog in Mainactivity in Android Studio?
i created a Java Class for my Dialog if the user is recording his sound.如果用户正在录制他的声音,我为我的对话框创建了 Java Class。 How can i react on the click of the stop-button?我如何对单击停止按钮做出反应? I want to stop the recording in my mainactivity then.我想在我的主要活动中停止录制。
Here's the code of my dialog:这是我的对话框的代码:
public class RecordDialog extends AppCompatDialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Recording...")
.setIcon(R.drawable.ic_record)
.setPositiveButton ("Stop", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
} }
MainActivity:主要活动:
public void openRecordDialog(View view) {
if (view.getId() == R.id.btnRec1) {
record();
RecordDialog recordDialog = new RecordDialog();
recordDialog.show(getSupportFragmentManager(), "Recording...");
}
}
private void record() {
try {
mediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
private void stop(){
mediaRecorder.stop();
mediaRecorder.release();
}
By clicking on a button in MainActivity the method openRecordDialog() will be started by onClick.通过单击 MainActivity 中的按钮,方法 openRecordDialog() 将由 onClick 启动。
How can i start the stop-method by clicking on positiveButton from Dialog?如何通过单击对话框中的正按钮来启动停止方法?
thx谢谢
I wonder, the best way to deal with the problem is to extract the interface you use to setup onclick from the onCreateDialog
method:我想知道,处理该问题的最佳方法是从onCreateDialog
方法中提取用于设置 onclick 的接口:
public class RecordDialog extends AppCompatDialogFragment {
private DialogInterface.OnClickListener OnStopListener;
public RecordDialog(DialogInterface.OnClickListener onStopListener){
//EDIT: calling super constructor to initialize the dialog properly
super();
OnStopListener = onStopListener;
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Recording...")
.setIcon(R.drawable.ic_record)
.setPositiveButton ("Stop", OnStopListener);
return builder.create();
}
}
And then you use it like this:然后你像这样使用它:
public void openRecordDialog(View view) {
if (view.getId() == R.id.btnRec1) {
...
RecordDialog recordDialog = new RecordDialog(
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Calling your function to stop the recording
stop();
}
}
);
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.