How to Show Alert Dialog in Android
Android Layout Files
We use the Alert Dialog to display alert messages.The AlertDialog is a small window that opens and warns us about objects and makes selections based on our selection.
- File : res/layout/activity_main.xml
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.taha.marketapplication.MainActivity"> <Button android:id="@+id/show_dialog" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical|center_horizontal" android:text="Show" /> </LinearLayout> |
- The screen image looks like the following
MainActivity
- Alert dialog code to be displayed when the user presses this button
File : MainActivity.java
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public class MainActivity extends AppCompatActivity { final Context context = this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.show_dialog); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle("Alert Dialog"); alertDialog.setMessage("Hello"); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); } }); } } |
- The alert dialog will be displayed when the show button is pressed
- As you can see from the code, the dialog will close after you hit the arrow button(dialog.dismiss())
Recent Comments