【IT168技術】之前我們的文章中曾經介紹Dialog,實際上已經實現了提醒功能,在Android中,還可以通過Toast(提醒)和Notification(通知)來實現提醒功能。和Dialog相比,這種提醒更加友好,並且不會打斷用戶的當前操作。本節詳細講解Toast和Notification控制項的級本概述,後續我們會介紹具體使用方法。
Toast簡介
Toast是Android中用來顯示信息的一種機制,和Dialog不一樣的是,Toast 是沒有焦點的,而且Toast顯示的時間有限,過一定的時間就會自動消失。例如,在下面的代碼中,編寫了Activity的子類別ToastDemo。
package com.a3gs.toast;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ToastDemo extends Activity {
private EditText myET;
private Button myBtn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myET = (EditText) findViewById(R.id.myET);
myBtn = (Button) findViewById(R.id.myBtn);
myBtn.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(ToastDemo.this, "您所填的信息是:" +
myET.getText ().toString(), Toast.LENGTH_LONG).show();
myET.setText("");
}
});
}
}
然後編寫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:text="@string/myText"
/>
<EditText
android:id="@+id/myET"
android:layout_width="180px"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/myBtn"
android:layout_width="100px"
android:layout_height="wrap_content"
android:text="@string/BtnText"
/>
</LinearLayout>
這樣,就簡單使用了Toast實現了提示功能。執行後的初始效果如圖6-61所示;輸入信息並單擊「發送」按鈕後,會以提示的方式顯示輸入的數據,如圖6-62所示。
▲