Alert Dialog (Hộp thoại cảnh báo) trong Android
Dialog có thể coi là một thông báo mà người dùng có thể tương tác trực tiếp được. Ví dụ khi các bạn muốn xóa một tập tin quan trọng hay muốn thoát một chương trình nào đấy thì việc hiển thì một thông báo để người dùng chắc chắn về hành vi của mình là rất quan trọng.
Android AlertDialog gồm có 3 vùng: Tiêu đề (title), nội dung(content) và các button hành động.
Android AlertDialog là lớp con của dialog
Để tạo Alert Dialog thường sử dụng thành phần AlertDialog.Builder
AlertDialog.Builder được sử dụng để tạo ra một giao diện là một hộp thoại cảnh báo trong Android. Thường thì chúng ta phải thiết lập các vùng:Tiêu đề, nội dung, image, button và xử lý sự kiện cho button.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
Các phương thức thường dùng trong Alert Dialog
1. setTitle(CharSequence title) – Phương thức này thường dùng để thiết lập tiêu đề cho Alert Dialog. Phương thức này tùy chọn.
//Thiết lập tiêu đề cho alert dialog alertDialogBuilder.setTitle("Xác nhận để thoát..!!!");
2. setIcon(Drawable icon) – Phương thức này dùng để thêm icon trước tiêu đề. Icon phài được lưu trong thư mục drawable.
// Icon Of Alert Dialog alertDialogBuilder.setIcon(R.drawable.question);
3. setMessage(CharSequence message) – Phương thức này dùng hiển thị nôi dung trong Alert Dialog. Nội dung này bắt buộc phải có.
// Setting Alert Dialog Message alertDialogBuilder.setMessage("Bạn có chắc thoát?");
4. setCancelable(boolean cancelable) – Phương thức này có 2 giá trị true/false. Nếu thiết lập false thì khi show dialog lên người dùng click ra bên ngoài dialog thì nó vẫn không bị mất, nếu set true thì sẽ mất khi click vào bất kì đâu ngoài dialog.
alertDialogBuilder.setCancelable(false);
5. setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener) – Phương thức này thiết lập một Button Positive (dương), mà dương thì nó nằm bên phải.
alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { // Đóng activity hiện tại finish(); } });
6. setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener) – Phương thức này thiết lập một Button Negative (âm), mà âm thì nó nằm bên trái.
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this,"You clicked over No",Toast.LENGTH_SHORT).show(); } });
7. setNeutralButton(CharSequence text, DialogInterface.OnClickListener listener) – Phương thức này đơn giản là thêm một Button mới, với button này chúng ta có thể xử lý sự kiện cho nó.Ví dụ 2 phương thức trên bạn đã thiết lập 2 Button "Yes" và "No" trong phương thức này chúng ta thiết lập Button "Cancel".
Ví dụ: Trong ví dụ này chúng ta sẽ làm ứng dụng gồm 1 Button. Khi người sử click vào Button "Thoát" sẽ xuất hiện một Alert Dialog. Tiến hành tạo project, vào thư mục res /layout -> activity_main.xml thiết kế giao diện sau:
Bước 1: Tạo một project tên là AlertDialog: File->New->Android Application Project điền các thông tin ->Next ->Finish
Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml và thêm code, chúng ta sẽ tạo các đối tượng Buton trong Relative Layout.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.alertdialogexample.MainActivity"> <Button android:text="Thoát" android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/button" android:onClick="exit" android:textStyle="normal|bold" android:background="#f00" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="131dp"/> <TextView android:text="Click vào Nút Thoát" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="68dp" android:id="@+id/textView2" android:layout_above="@+id/button" android:layout_centerHorizontal="true" android:textSize="18sp" android:textStyle="normal|bold" android:gravity="center" /> </RelativeLayout>
Bước 4: Mở app -> src ->MainActivity.java và thêm code.
Trong bước này chúng ta sử dụng AlertDialog.Builder để tạo hộp thoại gồm: Tiêu đề, nội dung, icon
package hiepsiit.com.alertdialog; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void exit(View view){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); // Setting Alert Dialog Title alertDialogBuilder.setTitle("Xác nhận để thoát..!!!"); // Icon Of Alert Dialog alertDialogBuilder.setIcon(R.drawable.question); // Setting Alert Dialog Message alertDialogBuilder.setMessage("Bạn có muốn thoát?"); alertDialogBuilder.setCancelable(false); alertDialogBuilder.setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { //Đóng Activity hiện tại finish(); } }); alertDialogBuilder.setNegativeButton("Không đồng ý", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this,"Bạn đã click vào nút không đồng ý",Toast.LENGTH_SHORT).show(); } }); alertDialogBuilder.setNeutralButton("Hủy", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(),"Bạn đã click vào nút hủy",Toast.LENGTH_SHORT).show(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } }
Ứng dụng này được phát triển bởi adt bundle, android 4.2 sử dụng minimum sdk 11 and target sdk 21.
Kết quả khi chạy ứng dụng:
Sau đó click vào Button "Thoát":
Cập nhật công nghệ từ Youtube tại link: https://www.youtube.com/channel/UCOxeYcvZPGf-mGLYSl_1LuA/videos
Để tham gia khóa học công nghệ truy cập link: http://thuvien.hocviendaotao.com
Mọi hỗ trợ về công nghệ email: dinhanhtuan68@gmail.com