技术开发 频道

Android开发之:Toast和Notification

  【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所示。

Android平台Toast简介

0
相关文章