[ Android ] Sử dụng hộp thoại Alert Dialog trong Android [Android Alert Dialog]

Một số lần trong ứng dụng của bạn, nếu bạn muốn yêu cầu người dùng đưa ra quyết định lựa chọn giữa Yes hoặc No đáp ứng của bất kỳ hành động cụ thể thực hiện bởi người sử dụng, bởi còn lại trong các hoạt động tương tự và không có thay đổi màn hình, bạn có thể sử dụng Alert Dialog.

Để sử dụng Alert Dialog bạn cần khai báo đối tượng AlertDialogBuilder. Cú pháp như sau:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

Bây giờ bạn phải thiết lập các nút Yes hoặc No bằng cách sử dụng đối tượng của lớp AlertDialogBuilder. Cú pháp như sau:

alertDialogBuilder.setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener) alertDialogBuilder.setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener)

Ngoài ra, bạn có thể sử dụng các chức năng khác được cung cấp bởi các lớp xây dựng để tùy chỉnh các hộp thoại cảnh báo. Dươi đây là những thuộc tính hay sử dụng:

Phương thức - mô tả

1- setIcon(Drawable icon)
Phương thức này để đặt icon cho hộp thoại.

2- setCancelable(boolean cancelable)
Phương thức này thiết lập thuoocjt ính cho hộp thoại có thể hủy bỏ học không

3- setMessage(CharSequence message)
Phương thức này thiết lập thông báo hiển thị trên hộp thoại.

4- setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)
Phương thức này thiết lập danh sách các phần tử để hiển thị trong hộp thoại

5- setOnCancelListener(DialogInterface.OnCancelListener onCancelListener)
Phương thức này thiết lập gọi trở lại nếu cancel

6- setTitle(CharSequence title)
Phương thức này thiết lập tiêu đề của hộp thoại

Cú pháp để tạo ra và hiển thị một hộp thoại
AlertDialog alertDialog = alertDialogBuilder.create(); 
alertDialog.show();

Ví dụ:
Ví dụ sau đây cho thấy việc sử dụng các AlertDialog trong Android. Sử dụng 3 active khác nhau.


1. Tạo Project như hình vẽ:




2. Viết code cho các file
*Code: src/com.example.alertdialog/MainActivity.java

package com.example.alertdialog; 
 import com.example.alertdialog.*; 
 import android.os.Bundle; 
 import android.app.Activity; 
 import android.app.AlertDialog; 
 import android.content.DialogInterface; 
 import android.content.Intent; 
 import android.view.Menu; 
 import android.view.View; 

 public class MainActivity extends Activity 
  @Override 
  protected void onCreate(Bundle savedInstanceState) 
  { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
  } 
public void open(View view)
{  
  AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);    
  alertDialogBuilder.setMessage(R.string.decision); 
  alertDialogBuilder.setPositiveButton(R.string.positive_button, new   DialogInterface.OnClickListener() 
  @Override 
 public void onClick(DialogInterface arg0, int arg1) 
 { 
    Intent positveActivity = new Intent(getApplicationContext(),com.example.alertdialog.PositiveActivity.class);
 startActivity(positveActivity); 
 } 
 }); 
 alertDialogBuilder.setNegativeButton(R.string.negative_button, new DialogInterface.OnClickListener() 
 @Override 
 public void onClick(DialogInterface dialog, int which) 
  Intent negativeActivity = new Intent(getApplicationContext(),com.example.alertdialog.NegativeActivity.class);
 startActivity(negativeActivity); } }); AlertDialog alertDialog = alertDialogBuilder.create(); 
 alertDialog.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.main, menu); 
 return true; 
 } 
}
*Code: src/com.example.alertdialog/PositiveActivity.java

package com.example.alertdialog; 
 import android.os.Bundle; 
 import android.app.Activity; 
 import android.view.Menu; 
 public class PositiveActivity extends Activity 
 @Override 
protected void onCreate(Bundle savedInstanceState) 
 super.onCreate(savedInstanceState); 
 setContentView(R.layout.activity_positive); 
 } 
 @Override 
 public boolean onCreateOptionsMenu(Menu menu) 
{
 // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.positive, menu); 
 getMenuInflater().inflate(R.menu.main, menu); 
 return true; 
 } 
 }

*Code: src/com.example.alertdialog/NegativeActivity.java

package com.example.alertdialog;
 import android.os.Bundle;
 import android.app.Activity;
 import android.view.Menu;
 public class NegativeActivity extends Activity
 { 
 @Override 
protected void onCreate(Bundle savedInstanceState) 
 super.onCreate(savedInstanceState); 
 setContentView(R.layout.activity_negative); 
 } 
 @Override 
 public boolean onCreateOptionsMenu(Menu menu) 
// Inflate the menu; this adds items to the action bar if it is present.
 //getMenuInflater().inflate(R.menu.negative, menu);
 getMenuInflater().inflate(R.menu.main, menu); 
 return true; 
 } 
 }

*Code: res/layout/activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   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=".MainActivity" >

  <Button
     android:id="@+id/button1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignParentTop="true"
     android:layout_centerHorizontal="true"
     android:layout_marginTop="170dp"
     android:onClick="open"
     android:text="@string/hello_world" />

</RelativeLayout>


*Code: res/layout/activity_negative.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   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=".NegativeActivity" >

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true"
      android:layout_marginLeft="14dp"
      android:layout_marginTop="17dp"
      android:text="@string/negative"
      android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

*Code: res/layout/activity_positive.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   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=".PositiveActivity" >

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true"
      android:layout_marginLeft="14dp"
      android:layout_marginTop="20dp"
      android:text="@string/positive"
      android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

*Code: Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">AlertDialog</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="title_activity_positive">PositiveActivity</string>
   <string name="title_activity_negative">NegativeActivity</string>
   <string name="positive">Positive Activity</string>
   <string name="negative">Negative Activity</string>
   <string name="decision">Are you sure, you wanted to make this decision</string>
   <string name="positive_button">+ive</string>
   <string name="negative_button">-ive</string>

</resources>

*Code: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.alertdialog"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.alertdialog.MainActivity"
         android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      <activity
         android:name="com.example.alertdialog.PositiveActivity"
         android:label="@string/title_activity_positive" >
      </activity>
      <activity
         android:name="com.example.alertdialog.NegativeActivity"
         android:label="@string/title_activity_negative" >
      </activity>
</application>

</manifest>

Kết quả:






*******

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Giáo trình: Lập Trình Android [Click để xem]

# Khoá học online:  Lập trình Android toàn tập [Click để xem]


Tham khảo tutorialspoint.com

Categories

AI (13) AI programming (1) ASP (1) Android (31) App Honeygain (4) Assembly (17) Biểu diễn thuật toán (1) Bubble-Sort (1) Bài giảng (2) Bài giảng lập trình C và Cpp (21) Bài viết hay (104) Bản đồ tư duy (1) C Plus Plus (103) C/C++ (16) CDSL phân tán (1) CSS (2) Cơ sở dữ liệu (11) Danh ngôn lập trình (1) Datamining (4) Genetic Algorithm (1) Giáo trình (2) Giải thuật tiến hóa - thuật toán di truyền (2) Google App Engine (2) Góc học tập (34) HTML (1) Hướng dẫn kiếm tiền online tại nhà (6) Hướng dẫn sử dụng Emu8086 (1) Học lập trình (131) Học lập trình C và CPP qua ví dụ (17) Java (54) Java Căn bản (6) JavaScript (5) Kỹ năng đọc hiệu quả (1) Kỹ thuật lập trình (16) Kỹ thuật đồ họa máy tính (10) Lý thuyết Cơ sở dữ liệu (2) Lý thuyết đồ thị (11) Lập trình Cơ sở dữ liệu (2) Lập trình Python (2) Lập trình căn bản (8) Lập trình hướng đối tượng với Java (7) Lập trình mobile (7) Lập trình mạng (6) Lập trình nhúng (1) Lập trình trí tuệ nhân tạo (2) ML (1) MMO (6) MS Access (1) Machine learning (2) Mạng máy tính (1) Mẹo tìm kiếm trên Google (1) Nghiên cứu khoa học (2) Ngôn ngữ lập trình (2) Những cuốn sách hay mà bạn nên đọc khi còn trẻ (1) Pascal (3) Phương pháp tính toán tối ưu (2) Phương pháp tối ưu (2) Quản lý dự án CNTT (1) SEO (1) SQL (5) Swift (9) Sách hay (4) Thiết kế Web (2) Thuật toán (51) Thuật toán Sắp Xếp -Sort (9) Thuật toán Tìm kiếm - Search (5) Thuật toán di truyền (4) Thực hành Android (2) Tin học văn phòng (5) Tiện ích máy tính (3) Toán rời rạc (13) Treo máy kiếm tiền (3) Trí tuệ nhân tạo (18) Tài liệu tham khảo (4) Tìm hiểu Blockchain (2) Tự học Android (3) Tự học Android qua ví dụ (1) Tự học JavaScript (1) Tự học lập trình (7) Tự học lập trình Android (17) Tự học lập trình C và CPP (14) Tự học lập trình java qua các ví dụ (8) XML (1) blockchain (2) bài giảng quản lý dự án CNTT (1) bài tập java (3) bài tập lập trình (4) cấu trúc dữ liệu giải thuật (15) hướng dẫn viết báo (1) học lập trình Java (11) học máy (5) hợp ngữ (8) lập trình viên (3) phưng pháp đơn hình (2) thuật toán AI (2) tài liệu CNTT miễn phí (3) tính toán tối ưu (1) tự học lập trình iOS (8) tự học lập trình python (1) ví dụ Assembly (1) Đại số gia tử và ứng dụng (1) Đồ họa (4)