在android studio的mainactivity中,如何从对话框做出React?

mu0hgdu0  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(364)

如果用户正在录制声音,我为对话框创建了一个java类。单击“停止”按钮时我有何React?我想停止我主要活动的录音。
下面是我的对话代码:

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();
}

}
主要活动:

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();

}

单击mainactivity中的按钮,onclick将启动openrecorddialog()方法。
如何通过单击对话框中的positivebutton来启动stop方法?
谢谢

8cdiaqws

8cdiaqws1#

我想知道,处理这个问题的最佳方法是从 onCreateDialog 方法:

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();
    }
}

然后你像这样使用它:

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();
                }
            }
        );
        ...
    }
}

相关问题