Search code examples
androiddialogandroid-dialogandroid-dialogfragmentdialogfragment

Showing a DialogFragment object from an on click inside a button listener


I was just trying showing a DialogFragment object from an on click inside a button listener.

Here is the code of the activity that should start the Dialog:

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    addListenerToButton1();
}

private void addListenerToButton1(){
    final Context context = this;


    button1 = (Button) findViewById(R.id.button1);

    button1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {

            DP ciao = new DP();
            ciao.show(this,"MyDP");
        }
    });
}
}

And here's the code of the Dialog:

public class DP extends DialogFragment {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the Builder class for convenient dialog construction
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    builder.setMessage("Prova")
    .setPositiveButton("POS", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {

        }
    })
    .setNegativeButton("NEG", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {

        }
    });
    return builder.create();
}
}

Errors are:

  • The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (MainActivity, String)

  • The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (new View.OnClickListener(){}, String)

Any advice?


Solution

  • Try this method of passing the correct context into your DialogFragment

    button1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
    
            DP ciao = new DP();
            ciao.show(view.getContext(),"MyDP");
        }
    });
    

    In your original code, when calling

    'ciao.show(this,"MyDP");'
    

    the this refers to its parent class which is OnClickListener.

    When assigning a click listener and overriding the onClick, you get passed the view and an argument which you can use to access information from, including the context.