OSbOoL
OSbOoL

Reputation: 13

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. 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.

How can i start the stop-method by clicking on positiveButton from Dialog?

thx

Upvotes: 0

Views: 356

Answers (1)

romamiyk
romamiyk

Reputation: 11

I wonder, the best way to deal with the problem is to extract the interface you use to setup onclick from the onCreateDialog method :

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

Upvotes: 1

Related Questions