Header ads

Header ads
» » Toast

Toast và tùy chỉnh Toast trong Android

Trong Android, Toast dùng để hiển thị thông tin trong khoảng thời gian ngắn.nó giống như một thông báo nổi trên ứng dụng, không ngăn cản tương tác người dùng. chúng ta có thể tùy biến lại Toast

Lớp android.widget.Toast là lớp con của lớp java.lang.Object.Chúng ta không thể tùy biến Toast trong tập tin xml

 


Các phương quan trọng của Toast

1. makeText(Context context, CharSequence text, int duration): Phương thức này thường sừ dụng để hiện thị thông báo. Phương thức này có 3 tham số:

Context context: thường là YourActitivty.this của bạn vào nếu như bạn đang sử dụng ở Activity, nếu như bạn sử dụng ở Fragment thì điền vào đó là getActivity().

CharSequence text:  đây chính là nội dung bạn muốn show lên, ở đây là kiểu String 

int duration: Khoảng thời gian Toast cần hiển thị, nó là hằng số.

Hằng số của Toast: Dưới đây là các hằng số của Toast được sử dụng để thiết lập thời gian cho Toast.

1. LENGTH_LONG: Toast sẽ hiển thị trong 3,5 giây

2. LENGTH_SHORT: Toast sẽ hiển thị trong 2 giây.

Ví dụ sau chúng ta dùng phương thức makeText để hiển thị thông báo, thiết lập thời gian hiển thị là 3,5 giây:

  Toast toast = Toast.makeText(getApplicationContext(), "Ví dụ Toast", Toast.LENGTH_LONG); // khởi tạo một Toast gồm 1 ngữ cảnh, nội dung, thời gian hiển thị

2. show(): phương thức này hiển thị thông báo ra màn hình. Phương pháp này hiển thị thông báo bằng cách sử dụng phương thức makeText() của Toast.

Ví dụ: Trước tiên chúng ta khởi tạo Toast và sau đó hiển thị nó bằng cách sử dụng phương thức show ().

  Toast toast = Toast.makeText(getApplicationContext(), "Ví dụ về Toast", Toast.LENGTH_LONG); // Khởi tạo Toast, thông tin hiển thị, thời gian 3,5 giây  toast.show(); // Hiển thị Toast

3. setGravity(int,int,int): Mặc định Toast sẽ hiển thị  ở dưới cùng của màn hình theo chiều ngang, nhưng bạn có tể thay đổi vị trí này bằng cách setGravity(int, int, int)

Ví dụ: Trước tiên chúng ta khởi tạo Toast và sau đó thiết lập vị trí của Toast top và left, sau đó, hiển thị nó bằng cách sử dụng phương thức show ().

  Toast toast = Toast.makeText(getApplicationContext(), "Ví dụ về Toast", Toast.LENGTH_LONG); // Khởi tạo Toast, thông tin hiển thị, thời gian 3,5 giây  toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);     // set gravity for the Toast.  toast.show(); // Hiển thị Toast

4. setText (CharSequence s): Phương thức này được sử dụng để thiết lập chuỗi thông báo cho Toast. Nếu chúng ta sử dụng phương thức makeText () và sau đó chúng ta muốn thay đổi chuỗi thông báo cho Toast thì chúng ta sử dụng phương thức này.

Ví dụ: Trước tiên chúng ta tạo mới Toast bằng cách dùng phương thức makeText() và sau đó thiết lập chuỗi thông báo mới cho Toast.

  Toast toast = Toast.makeText(getApplicationContext(), "Ví dụ về Toast", Toast.LENGTH_LONG); // Khởi tạo Toast, thông tin hiển thị, thời gian 3,5 giây  toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);     // set gravity for the Toast.  toast.setText("Thay đổi chuỗi thông báo"); // set the text for the Toast  toast.show(); // Hiển thị Toast

5. setDuration(int duration): Phương thức này được sử dụng để thiết lập thời gian hiển thị trên màn hình cho Toast. Nếu chúng ta sử dụng phương thức makeText () và sau đó chúng ta muốn thay đổi thời gian hiển thị cho Toast thì chúng ta sử dụng phương thức này.

Ví dụ: Trước tiên chúng ta tạo mới Toast bằng cách dùng phương thức makeText() và sau đó thiết lập thời gian hiển thị mới cho Toast.

  Toast toast = Toast.makeText(getApplicationContext(), "Ví dụ về Toast", Toast.LENGTH_LONG); // Khởi tạo Toast, thông tin hiển thị, thời gian 3,5 giây  toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);     // set gravity for the Toast.  toast.setDuration(Toast.LENGTH_SHORT); // set the duration for the Toast.  toast.show(); // Hiển thị Toast

6. inflate(int, ViewGroup): Phương thức làm công việc chuyển mã từ một file layout xml lên view. Tham số đầu tiên resource trỏ đến layout muốn inflate vào view, Tham số thứ 2 là gốc của cả cây layout mà bạn muốn add view này vào.

Ví dụ sau đây chúng ta chuyển từ một tập tin xml lên view

  // Retrieve the Layout Inflater and inflate the layout from xml  LayoutInflater inflater = getLayoutInflater();  View layout = inflater.inflate(R.layout.custom_toast_layout,  (ViewGroup) findViewById(R.id.toast_layout_root));

7. setView(View): Phương thức này thường dùng thiết lập view cho Toast. Ví dụ sau trước tiên chúng ta lấy layout từ tập tin xml, sau đó tạo một Toast rồi truyền layout này cho Toast bằng cách dùng phương thức setView()

  // Retrieve the Layout Inflater and inflate the layout from xml  LayoutInflater inflater = getLayoutInflater();  View layout = inflater.inflate(R.layout.custom_toast_layout,  (ViewGroup) findViewById(R.id.toast_layout_root));    // create a new Toast using context  Toast toast = new Toast(getApplicationContext());  toast.setDuration(Toast.LENGTH_LONG); // set the duration for the Toast  toast.setView(layout); // set the inflated layout  toast.show(); // display the custom Toast

 


Các bước tùy chỉnh một Toast

Bước 1: Lấy tập tin xml của layout bằng phương thức getLayoutInflater()  (or getSystemService()), sau đó đổ layout vào view bằng phương thức inflate(int, ViewGroup). Trong phương thức này tham số đầu tiên resource trỏ đến layout muốn inflate vào view, Tham số thứ 2 là gốc của cả cây layout mà bạn muốn add view này vào.

Bước 2: Tạo mới một Toast bằng đối tượng Toast(Context) và thiết lập vài thuộc tính : Thời gian hiển thị, vị trí của Toast.

Bước 3: Gọi phương thức setView(View) và truyền layout cho phương thức này.

Bước 4: Dùng phương thức show() của Toast để hiển thị Toast ra màn hình.


Ví dụ: Trong ví dụ này chúng ta sẽ làm ứng dụng gồm 2 Button. Khi người sử click vào Button "Simple Toast" sẽ xuất hiện một toast mặc định, Click vào  Button "Custom Toast" Xuất hiện một toast đã tùy biến. 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à ToastDemoFile->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.

  <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's for simple and custom Toast -->  <Button  android:id="@+id/simpleToast"  android:layout_width="200dp"  android:layout_height="wrap_content"  android:layout_centerHorizontal="true"  android:layout_marginTop="150dp"  android:background="#f00"  android:text="Simple Toast"  android:textColor="#fff"  android:textSize="20sp" />    <Button  android:id="@+id/customToast"  android:layout_width="200dp"  android:layout_height="wrap_content"  android:layout_below="@+id/simpleToast"  android:layout_centerHorizontal="true"  android:layout_margin="50dp"  android:background="#0f0"  android:text="Custom Toast"  android:textColor="#fff"  android:textSize="20sp" />    </RelativeLayout>

Bước 3: Trong bước này chúng ta tạo một layout. Click - right  trên res/layout -> New -> Layout Resource File và đặt tên là custom_toast_layout.xml

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:id="@+id/toast_layout_root"  android:layout_width="fill_parent"  android:layout_height="fill_parent"  android:background="#DAAA"  android:orientation="horizontal"  android:padding="8dp">  <!-- ImageVView and TextView for custom Toast -->  <ImageView  android:id="@+id/toastImageView"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:layout_marginRight="8dp" />    <TextView  android:id="@+id/toastTextView"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:textColor="#FFF" />  </LinearLayout>

Bước 4: Mở app -> src ->MainActivity.java và thêm code.

  package hiepsiit.com.toastdemo;    import android.app.Activity;  import android.os.Bundle;  import android.view.Gravity;  import android.view.LayoutInflater;  import android.view.Menu;  import android.view.MenuItem;  import android.view.View;  import android.view.View.OnClickListener;  import android.view.ViewGroup;  import android.widget.Button;  import android.widget.ImageView;  import android.widget.TextView;  import android.widget.Toast;    public class MainActivity extends Activity implements OnClickListener{  	Button simpleToast, customToast;    	@Override  	protected void onCreate(Bundle savedInstanceState) {  		super.onCreate(savedInstanceState);  		setContentView(R.layout.activity_main);  		// get the reference of Button's          simpleToast = (Button) findViewById(R.id.simpleToast);          customToast = (Button) findViewById(R.id.customToast);          // perform setOnClickListener event on simple Toast Button          simpleToast.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View v) {                  // initiate a Toast with message and duration                  Toast toast = Toast.makeText(getApplicationContext(), "Simple Toast In Android", Toast.LENGTH_LONG); // initiate the Toast with context, message and duration for the Toast                  toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);     // set gravity for the Toast.                  toast.show(); // display the Toast                }          });          // perform setOnClickListener event on custom Toast Button          customToast.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View v) {                  // Retrieve the Layout Inflater and inflate the layout from xml                  LayoutInflater inflater = getLayoutInflater();                  View layout = inflater.inflate(R.layout.custom_toast_layout,                          (ViewGroup) findViewById(R.id.toast_layout_root));                  // get the reference of TextView and ImageVIew from inflated layout                  TextView toastTextView = (TextView) layout.findViewById(R.id.toastTextView);                  ImageView toastImageView = (ImageView) layout.findViewById(R.id.toastImageView);                  // set the text in the TextView                  toastTextView.setText("Custom Toast In Android");                  // set the Image in the ImageView                  toastImageView.setImageResource(R.drawable.ic_launcher);                  // create a new Toast using context                  Toast toast = new Toast(getApplicationContext());                  toast.setDuration(Toast.LENGTH_LONG); // set the duration for the Toast                  toast.setView(layout); // set the inflated layout                  toast.show(); // display the custom Toast                }          });      }	  	  }  

 


Download ví dụ

Ứng dụng này được phát triển bởi adt bundleandroid 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 "CUSTOM TOAST":



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

About Học viện đào tạo trực tuyến

Xinh chào bạn. Tôi là Đinh Anh Tuấn - Thạc sĩ CNTT. Email: dinhanhtuan68@gmail.com .
- Nhận đào tạo trực tuyến lập trình dành cho nhà quản lý, kế toán bằng Foxpro, Access 2010, Excel, Macro Excel, Macro Word, chứng chỉ MOS cao cấp, IC3, tiếng anh, phần mềm, phần cứng .
- Nhận thiết kế phần mềm quản lý, Web, Web ứng dụng, quản lý, bán hàng,... Nhận Thiết kế bài giảng điện tử, số hóa tài liệu...
HỌC VIỆN ĐÀO TẠO TRỰC TUYẾN:TẬN TÂM-CHẤT LƯỢNG.
«
Next
Bài đăng Mới hơn
»
Previous
Bài đăng Cũ hơn