Saturday, July 19, 2014

Bài 10:Custom Toast và Aler Dialog trong android



   Chào các bạn! Trong bài trước tôi có giới thiệu cho các bạn 2 cách để thông báo tới người dùng là Toast Notification và Aler Dialog.Nếu bạn thấy giao diện của nó quá "củ chuối" thì trong bài hôm nay tôi sẽ hướng dẫn các bạn "Custom" nó theo ý của mình.

   CUSTOM TOAST NOTIFICATION

Giao diện chính sẽ như sau:
Khi nhấn từng button sẽ hiện ra các Toast khác nhau.
-Tạo một Project mới có tên ToastCustom
-Trong file activity_main:
<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" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="49dp"
        android:text="Custom Toast"
        android:textStyle="bold"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="58dp"
        android:layout_toLeftOf="@+id/textView1"
        android:text="Kiểu 1" />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_toRightOf="@+id/textView1"
        android:onClick="custom_2"
        android:text="Kiểu 2" />
</RelativeLayout>


 -Tạo một file có tên custom_toast trong folder layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:orientation="vertical"
    android:padding="10dp"
    android:background="#ff0000" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Custom toast với nền màu đỏ"
        android:textColor="#ffffff"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

-Cuối cùng trong Class MainActivity:
package com.example.toastcustom;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
    Button btn1;                //custom toast 1
  
    Button btn2;                //custom toast 2
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      
        btn1=(Button)
                findViewById(R.id.button1);            //lấy id từ file xml
      
        btn1.setOnClickListener(new OnClickListener() {            //Bắt sự  kiện nhấn vào nút thứ nhất
          
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
              
                Toast toast=Toast.makeText(MainActivity.this, "Custom Toast kiểu 1", Toast.LENGTH_LONG);
              
                int gravity=Gravity.BOTTOM;        //Hiển thị ở trên màn hìn,ngoài ra còn left,right....
              
                int xOffset=0;                    //Hiển ở vị trí 0 theo chiều ngang màn hình (Chấp nhận giá trị âm)
              
                int yOffset=0;                    //Hiển ở vị trí 0 theo chiều dọc màn hình
              
                toast.setGravity(gravity, xOffset, yOffset);  
              
                toast.show();  //Show Toast notification;
            }
        });
    }
      
        //Bắt sự kiện click ở button 2
        public void custom_2(View v){
            //lấy file xml để custom Toast
            LayoutInflater inflater=(LayoutInflater)
                                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view=inflater.inflate(R.layout.custom_toast, null);
          
            Toast toast=new Toast(MainActivity.this);
          
            toast.setView(view);    //custom Toast
          
            toast.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;
    }
}
-Cuối cùng nhấn ctrl+F11 để chạy!
Kết quả:


-Khi ta thay giá trị xOffset thành -100 sẽ có:

Dowload source code:custom toast


  Custom AlerDialog

Giao diện chính rất đơn giản:


Khi nhấn button nó đều cho kết quả giố nhau.Nhưng tôi làm theo 2 cách khác nhau:

-Bạn tạo một Project mới có tên Dialog_Custom

-Trong file activity_main:
<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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="71dp"
        android:text="Custom Dialog"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="25dp"
        android:text="Cách 1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="33dp"
        android:text="Cách 2" />

</RelativeLayout>

 -Tạo một file có tên alert_dialog trong folder layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="5dp" />

    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFF"
        android:layout_toRightOf="@+id/image"/>/>

     <Button
        android:id="@+id/dialogButtonOK"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text=" Đóng... "
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_below="@+id/image"
        />

</RelativeLayout>

-Cuối cùng trong Class MainActivity:
package com.example.dialog_custom;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {
    Context context=this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Cách 1
        Button c1=(Button)
                findViewById(R.id.button1);
        c1.setOnClickListener(new OnClickListener() {
          
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
            showDialog1();  
            }
        });
      
        //Cách 2
                Button c2=(Button)
                        findViewById(R.id.button2);
                c2.setOnClickListener(new OnClickListener() {
                  
                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                    showDialog2();  
                    }
                });
    }
  
    public void showDialog1(){
         final AlertDialog dialog=new AlertDialog.Builder(context).create();//Tạo dialog
      
        //lấy file xml từ folder layout
        LayoutInflater inflater=(LayoutInflater)
                                getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view=inflater.inflate(R.layout.alert_dialog, null);
      
        dialog.setView(view);        //set giao diện
      
        TextView text = (TextView) view.findViewById(R.id.text);            //Bạn chú ý view.findViewById()...Xác định nó là của dialog
        text.setText("Xin chào các bạn đến với lập trình Android!");
        ImageView image = (ImageView) view.findViewById(R.id.image);
        image.setImageResource(R.drawable.ic_launcher);

        Button dialogButton = (Button)    view.findViewById(R.id.dialogButtonOK);
        // if button is clicked, close the custom dialog
        dialogButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                dialog.dismiss();   //Ẩn dialog
            }
        });
      
        dialog.show();
    }
  
    public void showDialog2(){
        // custom dialog
        final Dialog dialog = new Dialog(context);
        dialog.setContentView(R.layout.alert_dialog);     //set giao diện cho dialog
        dialog.setTitle("Lập trình Android...");

        // set the custom dialog components - text, image and button
        TextView text = (TextView) dialog.findViewById(R.id.text);            //Bạn chú ý dialog.findViewById()...Xác định nó là của dialog
        text.setText("Xin chào các bạn đến với lập trình Android!");
        ImageView image = (ImageView) dialog.findViewById(R.id.image);
        image.setImageResource(R.drawable.ic_launcher);

        Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
        // if button is clicked, close the custom dialog
        dialogButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                dialog.dismiss();   //Ẩn dialog
            }
        });

        dialog.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;
    }

}
-Cuối cùng nhấn ctrl+F11 để chạy!
Kết quả:

Dowload source code:custom dialog

Mọi thắc mắc,góp y xin vui lòng comment bên dưới hoặc tại fan page:android

.

No comments:

Post a Comment