Bài 9. Toast và Dialog

 


1. Toast trong Android Studio

 

Toast là một loại thông báo (message) ngắn. Để hiển thị trong một khoảng thời gian nhất định và tự động mất dần.
Nó giúp người lập trình gỡ rối (debugging) cho chương trình khi cần thiết . Trong lúc hiển thị, không ảnh hưởng đến activity khác và không bắt các sự kiện của người dùng.

a. Tạo Giao diện trong tập tin XML
Mở tập tin res/layout/activity_main.xml và thêm đoạn mã sau:

  1. <LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    
        Android:id="@+id/LinearLayout1"
    
        Android:layout_width="fill_parent"
    
        Android:layout_height="fill_parent"
    
        Android:orientation="vertical"
    
       Android:layout_gravity="center"
    
       Android:gravity="center">
    
        <Button
    
            Android:id="@+id/button1"
    
            Android:layout_width="wrap_content"
    
            Android:layout_height="wrap_content"
    
            Android:text="Toast " 
    
            Android:gravity="center"
    
        />
    
    </LinearLayout>

     

  2. b. Viết code cho chương trình

Thêm sự kiện OnClickListener() cho Button . Khi người dùng click vào Button một thông báo xuất hiện.

Mở tập tin MainActivity.java và thêm đoạn mã sau:

Code:

public class MainActivity extends Activity {

Button button;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {

              public void onClick(View arg0) {

                Toast.makeText(getApplicationContext(),  "Bạn vừa Click vào button  Toast!!!",

 Toast.LENGTH_LONG).show();

              }

        });

    }

    }

 

Ví dụ: Dùng tablelayout tạo các button số từ 1 đến  9 khi click vào button sẽ hiện lên thông báo các số vừa chọn.

Mở tập tin res/layout/activity_main.xml và ta làm như sau:

Code trong Mainactivity.java

publicclass MainActivity extends Activity implements OnClickListener {

Button so1,so2,so3,so4,so5,so6,so7,so8,so9;

     @Override

protectedvoid onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

          setContentView(R.layout.activity_main);

          so1=(Button) findViewById(R.id.btn1);

          so2=(Button) findViewById(R.id.btn2);

          so3=(Button) findViewById(R.id.btn3);

          so4=(Button) findViewById(R.id.btn4);

          so5=(Button) findViewById(R.id.btn5);

          so6=(Button) findViewById(R.id.btn6);

          so7=(Button) findViewById(R.id.btn7);

          so8=(Button) findViewById(R.id.btn8);

          so9=(Button) findViewById(R.id.btn9);

          so1.setOnClickListener(this);

          so2.setOnClickListener(this);

          so3.setOnClickListener(this);

          so4.setOnClickListener(this);

          so5.setOnClickListener(this);

          so6.setOnClickListener(this);

          so7.setOnClickListener(this);

          so8.setOnClickListener(this);

          so9.setOnClickListener(this);

     }

void toast(String i)

{

       Toast.makeText(getApplicationContext(), "ban vua click so "+i+" ", Toast.LENGTH_LONG).show();

}

     @Override

publicvoid onClick(View arg0) {

          // TODO Auto-generated method stub

switch (arg0.getId()){

case R.id.btn1:

                toast("1");

break;

case R.id.btn2:

                toast("2");

break;

case R.id.btn3:

                toast("3");

break;

case R.id.btn4:

                toast("4");

break;

case R.id.btn5:

                toast("5");

break;

case R.id.btn6:

                toast("6");

break;

case R.id.btn7:

                toast("7");

break;

case R.id.btn8:

                toast("8");

break;

case R.id.btn9:

                toast("9");

break;

            }

     }

}

 


2. Dialog trong android studio

Một hộp thoại thường là một màn hình nhỏ  mà xuất hiện đè lên các Activity hiện tại. Activity nằm dưới sẽ  không tương tác được với người dùng mà thay vào đó là hộp thoại sẽ  đóng vai trò đó. Hộp thoại thông thường dùng để  thông báo hay đại loại vậy. Thông thường có các loại hộp thoại sau:

Tên dialogMiêu tả
AlertDialog Là dạng hộp thoại có nhiều nhất 3 nút nhấn hoặc có thêm danh sách các mục lựa chọn có thêm checkbox hay radio button. AlertDialog thích  hợp  làm  hộp  thoại  trong  các  chương  trình  Android  và  được  khuyến khích dùng.
ProgressDialog Là  hộp  thoại  có  vòng  xoay  hay  thanh  thể  hiện  tiến trình đang chạy. Bởi vì nó là dạng AlertDialog mở  rộng cho nên nó cũng có nút nhấn.

2.1  Tạo AlertDialog

Giao diện hiển thị của nó gồm nhiều thành phần như sau:

  • Tiêu đề. 
  • Thông điệp thông báo. 
  • Danh sách chứa các CheckBox hay Radio Button.
  • addialog

File activity_main.xml:

<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"

    Android:id="@+id/LinearLayout1"

    Android:layout_width="fill_parent"

    Android:layout_height="fill_parent"

    Android:orientation="vertical"

    Android:layout_gravity="center"

    Android:gravity="center">

    <Button

        Android:id="@+id/button1"

        Android:layout_width="wrap_content"

        Android:layout_height="wrap_content"

        Android:text="Dialog " 

         Android:gravity="center"

    /> 

</LinearLayout>

 

File MainActivity.java:

public class MainActivity extends Activity {

    final Context context = this;

    Button button;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

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

// gán tiêu đề cho dialog

                alertDialogBuilder.setTitle("Thoát");

// hiển thị Thông điệp (thông báo) lên dialog

                alertDialogBuilder .setMessage("Bạn có muốn thoát không ?")

                        .setCancelable(false)

                        .setPositiveButton("Có",new DialogInterface.OnClickListener()  {

                            public void onClick(DialogInterface dialog,int id) {

                                MainActivity.this.finish();

                            }

                        })

                        .setNegativeButton("Không",new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog,int id) {

                                dialog.cancel();

                            }

                        });

                // Tạo alert dialog

                AlertDialog alertDialog = alertDialogBuilder.create();

                // Hiển thị dialog

                alertDialog.show();

            }

        });

    }

 

Để khởi tạo AlertDialog, ta phải sử dụng lớp con là  AlertDialog.Builder:

AlertDialog.Builder build = new AlertDialog.Builder(context);

Sau khi build xong, thì gọi create để tạo object của AlertDialog từ builder đó:

AlertDialog ad = build.create();

 

Mục đíchPhương thức/Đối tượng
Tạo đối tượng để xây dựng AlertDialog AlertDialog.Builder builder = new AlertDialog.Builder(this);
Thiết lập tiêu đề setTitle(CharSequence title) hoặc setTitle(int titleId)
Thiết lập thông điệp

setMessage(CharSequence message) hoặc setMessage(int

messageId)

Thiết lập icon setIcon(Drawable icon) hoặc setIcon(int iconId)
Thiết lập danh sách

setItems(CharSequence[] items,

DialogInterface.OnClickListener listener) hoặc setItem(int

itemsId, DialogInterface.OnClickListener listener)

Thiết lập danh sách chứa Radio Buttons

setSingleChoiceItems(CharSequence[] items, int

checkedItem, DialogInterface.OnClickListener listener) hoặc

setSingleChoiceItems(int itemsId, int checkedItem,DialogInterface.OnClickListener listener)

Thiết lập danh sách chứa CheckBox

setMultiChoiceItems(CharSequence[] items, boolean[]

checkedItems, DialogInterface.OnClickListener listener) hoặc

setMultiChoiceItems(int itemsId, boolean checkedItems,DialogInterface.OnClickListener listener)

Thiết lập Positive Button

setPositiveButton(CharSequence text,

DialogInterface.OnClickListener listener) hoặc

setPositiveButton(int textId, DialogInterface.OnClickListenerlistener)

Thiết lập Negative Button

setNegativeButton(CharSequence text,

DialogInterface.OnClickListener listener) hoặc

setNegativeButton (int textId,DialogInterface.OnClickListener listener)

Thiết lập Neutral Button

setNeutralButton(CharSequence text,

DialogInterface.OnClickListener listener) hoặc

setNeutralButton (int textId, DialogInterface.OnClickListenerlistener)

 


2.2 Progress Dialog

ProgressDialog là loại Dialog dùng để hiển thị tiến độ thực hiện một công việc nào đó. Dạng Dialog này được tạo ra từ lớp cha là AlertDialog. Ngoài những tính chất riêng, nó cũng kế thừa nhiều thuộc tính từ lớp cha AlertDialog như : Tiêu đề, Thông điệp, Buttons.

  • Dạng xoay:
  • prodialog

Code :

public class MainActivity extends Activity {

       final Context context = this;

Button button;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button1);

        // add button listener

        button.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {

          ProgressDialog pd =

new ProgressDialog(MainActivity.this);

               pd.setTitle("Vui Lòng chờ......");    

              pd.setMessage("loading ");

              pd.show();

              }

            });

        }

    }

 

-Dạng thanh ngang

Code :

public class MainActivity extends Activity {

       final Context context = this;

Button button;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button1);

        // add button listener

        button.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {

          final ProgressDialog progressDialog1;

          progressDialog1 = new ProgressDialog(this);

                progressDialog1.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

progressDialog1.setMessage("Loading...");

progressDialog1.setCancelable(true);

progressDialog1.setProgress(0);

//Set tiến độ cho ProgressBar

 progressDialog1.setMax(100);//Set Giá trị cho tối đa cho ProgressBar

progressDialog1.show();

//Tạo Thread để tăng giá trị của Progress Bar theo thời gian chúng ta quy định

   new Thread(new Runnable() {

                    @Override

                    public void run() {

                        while(progressDialog1.getProgress()<= ProgressDialog1.getMax())

                        {

                            try

                            {

                                progressDialog1.incrementProgressBy(1);//Tăng Giá trị tiến độ

                                Thread.sleep(100);

                                if(progressDialog1.getProgress()== progressDialog1.getMax())// Nếu đạt tối đa

                                    progressDialog1.cancel();

                            }

                            catch(Exception ex)

                            {}

                        }

                    }

                }).start();              }

            });

        }

    }

 


2.3 Custom Dialog

Là dạng Dialog có giao diện theo thiết kế của người lậptrình,có thể bao gồm cả ImageView, TextView, EditText, v.v…

Ví dụ về các loại dialog:

Capture

Ngoài layout main ra ta tạo thêm 1 layout khác có tên là customdialog:

Customdialog.xml

<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:padding="10dp"  >

    <ImageView

        android:id="@+id/imgAndroid"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginRight="10dp" />

    <TextView

        android:id="@+id/txtContent"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textColor="#FFFF00"

        android:textSize="18sp"  />

</LinearLayout>

 

main.xml

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"    >

    <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:gravity="center"

        android:text="Các loại Dialog"

        android:textSize="20sp"

        android:textColor="#ff0b0cff"

        android:textStyle="bold"    />

    <TableLayout

        android:orientation="vertical"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:stretchColumns="*"     >

        <TableRow>

            <Button

                android:id="@+id/btnButtonDialog"

                android:layout_width="fill_parent"

                android:layout_height="wrap_content"

                android:text="Button Dialog"         />

            <Button

                android:id="@+id/btnListDialog"

                android:layout_width="fill_parent"

                android:layout_height="wrap_content"

                android:text="List Dialog"         />

        </TableRow>

        <TableRow>

            <Button

                android:id="@+id/btnRadioDialog"

                android:layout_width="fill_parent"

                android:layout_height="wrap_content"

                android:text="Radio Dialog"         />

            <Button

                android:id="@+id/btnCheckboxDialog"

                android:layout_width="fill_parent"

                android:layout_height="wrap_content"

                android:text="CheckBox Dialog"         />

        </TableRow>

        <TableRow>

            <Button

                android:id="@+id/btnProgressDialog"

                android:layout_width="fill_parent"

                android:layout_height="wrap_content"

                android:text="Progress Dialog"         />

            <Button

                android:id="@+id/btnProgressBar"

                android:layout_width="fill_parent"

                android:layout_height="wrap_content"

                android:text="Progress Bar"         />

        </TableRow>

        <TableRow>

            <Button

                android:id="@+id/btnCustomDialog"

                android:layout_width="fill_parent"

                android:layout_height="wrap_content"

                android:text="Custom Dialog"         />

        </TableRow>

        <TextView

            android:id="@+id/txtDisplay"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:textColor="#ffff162a"

            android:textSize="20sp"

            android:text="Click vào Button"     />

    </TableLayout>

</LinearLayout>

 

 

Code trong MainActivity.java

public class MainActivity extends Activity implements View.OnClickListener {

    Button buttonDialog,listDialog,radioDialog,checkboxDialog,progressDialog,progressBar,customDialog;

    TextView txtDisplay;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        buttonDialog = (Button) findViewById(R.id.btnButtonDialog);

        listDialog = (Button) findViewById(R.id.btnListDialog);

        radioDialog = (Button) findViewById(R.id.btnRadioDialog);

        checkboxDialog = (Button) findViewById(R.id.btnCheckboxDialog);

        progressDialog = (Button) findViewById(R.id.btnProgressDialog);

        progressBar = (Button) findViewById(R.id.btnProgressBar);

        customDialog = (Button) findViewById(R.id.btnCustomDialog);

        txtDisplay = (TextView) findViewById(R.id.txtDisplay);

        //Set Click

        buttonDialog.setOnClickListener(this);

        listDialog.setOnClickListener(this);

        radioDialog.setOnClickListener(this);

        checkboxDialog.setOnClickListener(this);

        progressDialog.setOnClickListener(this);

        progressBar.setOnClickListener(this);

        customDialog.setOnClickListener(this);

    }

    //mảng chuỗi sắp xếp tuần tự

    final CharSequence[] items = {"Android", "Java ", "PHP"};

    //Mảng chứa trạng thái các item

    final boolean[] states = {false, false, true};

    Handler handler = new Handler();

    @Override

    public void onClick(View v) {

        switch(v.getId())

        {

            case R.id.btnButtonDialog:

                txtDisplay.setText("");

                //Bạn có thể lược bỏ phần nào trong Dialog mà bạn thích: Tile, Message...

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

                builder.setTitle("Thoát");// Set tiêu đề

                builder.setMessage("Bạn có muốn thoát không ?");//Set nội dung cho Dialog

                builder.setCancelable(false);//Set có cho người dùng Cancer bằng nút quay lại (back) ko? false: ko

                builder.setPositiveButton("Có",new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface dialog, int which) {

                        //Làm cái gì đó khi ấn Yes tại đây

                        txtDisplay.setText("YES");

                        dialog.dismiss();

                    }

                });

                builder.setNegativeButton("Không", new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface dialog, int which) {

                        //

                        txtDisplay.setText("NO");

                        dialog.cancel();

                    }

                });

                builder.show();//Hiển thị Dialog

                break;

            case R.id.btnListDialog:

                txtDisplay.setText("");

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

                builder1.setTitle("Danh sách ngôn ngữ lập trình");

                builder1.setItems(items, new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface dialog, int item) {

                        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();//Hiển thị item được lựa chọn

                        txtDisplay.setText(items[item].toString());

                    }

                });

                builder1.show();

                break;

            case R.id.btnRadioDialog:

                txtDisplay.setText("");

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

                builder2.setTitle("Danh sách ngôn ngữ lập trình");

                //setSingleChoiceItems(CharSequence[] items, int checkedItem, OnClickListener listener):

                // -> checkedItem: Item muốn check mặc định, để giá trị -1 để ko chọn giá trị nào, vị trí bắt đầu từ 0

                builder2.setSingleChoiceItems(items,-1, new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface dialog, int item) {

                        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();//Hiển thị item được lựa chọn

                        txtDisplay.setText(items[item].toString());

                        dialog.dismiss();

                    }

                });

                builder2.show();

                break;

            case R.id.btnCheckboxDialog:

                txtDisplay.setText("");

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

                builder3.setTitle("Danh sách ngôn ngữ lập trình");

                builder3.setMultiChoiceItems(items, states, new DialogInterface.OnMultiChoiceClickListener() {

                    @Override

                    public void onClick(DialogInterface dialog, int item, boolean isChecked) {

                        Toast.makeText(getApplicationContext(), items[item] + " được gán là " + isChecked, Toast.LENGTH_SHORT).show();

                    }

                });

                builder3.show();

                break;

            case R.id.btnProgressDialog:

                //true: Có cho cancel Dialog

                //false: indeterminate (Vô hạn)

                ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this, "progress Dialog", "Please waiting ...",false, true, new DialogInterface.OnCancelListener() {

                    @Override

                    public void onCancel(DialogInterface dialog) {

                        txtDisplay.setText("Done");

                    }

                });

                progressDialog.show();

                break;

            case R.id.btnProgressBar:

                final ProgressDialog progressDialog1;

                progressDialog1 = new ProgressDialog(this);

                progressDialog1.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

                progressDialog1.setMessage("Loading...");

                progressDialog1.setCancelable(true);

                progressDialog1.setProgress(0);//Set tiến độ cho ProgressBar

                progressDialog1.setMax(100);//Set Giá trị cho tối đa cho ProgressBar

                progressDialog1.show();

                //Tạo Thread để tăng giá trị của Progress Bar theo thời gian chúng ta quy định

                new Thread(new Runnable() {

                    @Override

                    public void run() {

                        while(progressDialog1.getProgress() <= progressDialog1.getMax())

                        {

                            try

                            {

                                progressDialog1.incrementProgressBy(1);//Tăng Giá trị tiến độ

                                Thread.sleep(100);

                                if(progressDialog1.getProgress()== progressDialog1.getMax())// Nếu đạt tối đa

                                    progressDialog1.cancel();

                            }

                            catch(Exception ex)

                            {}

                        }

                    }

                }).start();

                break;

            case R.id.btnCustomDialog:

                Dialog dialog = new Dialog(MainActivity.this);

               dialog.setContentView(R.layout.customdialog); //Hiện thị Dialog với layout custom_Dialog

                dialog.setTitle("Custom Dialog");

                dialog.setCancelable(true);

                //Set Image

                ImageView imageView = (ImageView) dialog.findViewById(R.id.imgAndroid);

               imageView.setImageResource(R.drawable.ic_launcher);

                //Set Text for TextView

               TextView txtContent = (TextView) dialog.findViewById(R.id.txtContent);

                txtContent.setText("VD về Custom Dialog.");

                //Show Dialog

                dialog.show();

                break;

        }

    }

}