0

I am trying to make a custom dialog but am experiencing a problem. My app crashes when I push the button which shows the dialog.

Here is my code:

public class Cartas extends AppCompatActivity {

    Dialog myDialog;
    Button senmacho;
    Button cerrar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cartas);

        senmacho = (Button) findViewById(R.id.senmacho);
        senmacho.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                senamacho();
            }
        });
    }

    public void senamacho(){
        myDialog = new Dialog(Cartas.this);
        myDialog.setContentView(R.layout.macho);
        myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        cerrar = (Button) findViewById(R.id.cerrar);
        cerrar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myDialog.cancel();
            }
        });
        myDialog.show();
    }
}
Gene Z. Ragan
  • 2,643
  • 2
  • 31
  • 41
JR10
  • 11
  • 2

2 Answers2

0

Changing the line cerrar = (Button) findViewById(R.id.cerrar); into cerrar = (Button) myDialog.findViewById(R.id.cerrar); or into cerrar = myDialog.findViewById(R.id.cerrar); might solve this issue . . .

elyar abad
  • 771
  • 1
  • 8
  • 27
0

There is a very basic error. You should follow the code below.

Instead: of this:

public void senamacho(){
    myDialog = new Dialog(Cartas.this);
    myDialog.setContentView(R.layout.macho);
    myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    cerrar = (Button) findViewById(R.id.cerrar);
    cerrar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            myDialog.cancel();
        }
    });
    myDialog.show();
}

Use This

public void senamacho(){
    myDialog = new Dialog(Cartas.this);
    myDialog.setContentView(R.layout.macho);
    myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
   //modify the line bellow
    cerrar = (Button) myDialog.findViewById(R.id.cerrar);
    cerrar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            myDialog.cancel();
        }
    });
    myDialog.show();
}