How to create dialog box in android android dialog

Опубликовано: 27 Май 2026
на канале: Computer Science lectures and tutorials
786
1

How to create dialog box in android android dialog

hi, today lets see how to build a dialog in
android.
we will build a dialog with 2 buttons.
and add onclicklistener to each button
and display the results in a textview.
lets create a button
now add the event to the button.
now lets create the dialog box in the button
click
now we have created the dialog box.
lets set the message in the dialog box
now the message is been set.
then add the buttons, there are 2 buttons
positivebutton
negativebutton.

lets add positivebutton
the positive button has the caption "POSITIVE"
and when the button is clicked, the
onclicklistener should be fired.
we will make use of the textview to display
the options that are clicked in the dialog box

the same thing goes for the negative button

now the dialog is created, lets show the dialog.
lets run this.
kindly subscribe our channel for more videos.

package com.example.andtest;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AndTest extends Activity {
Button but;
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_and_test);
but=(Button) findViewById(R.id.button1);
txt=(TextView) findViewById(R.id.textView1);
but.setOnClickListener(new OnClickListener()
{

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
AlertDialog.Builder ab=new AlertDialog.Builder(AndTest.this);
ab.setMessage("Click on any button");
ab.setPositiveButton("POSITIVE",new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
txt.setText("You have clicked the positive button");
}
});

ab.setNegativeButton("NEGATIVE",new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
txt.setText("You have clicked the negative button");
}
});
AlertDialog ad=ab.create();
ad.show();

}

}
);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_and_test, menu);
return true;
}

}