Android中Toast对象的使用
编号:A3GS_TA20100115003
描述:
本文讲述了Android中Toast对象的使用。
例子:
有兴趣的朋友可以在登录后下载本文例子代码!
例子效果图:
实现步骤:
第一步:建立Android 工程:ToastDemo。
第二步:编写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("");
}
});
}
}
第三步:修改res/layout/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 显示后会在一定时间内消失,在Toast 构造参数中的第二个参数为显示的时间常数,可设置为LENGTH_LONG 或LENGTH_SHORT,前者提示时间较长,后者较短,作为传递makeText() 方法的参数使用。
当然,你也可以使用重写 Toast 对象的方法,自定义Toast 显示的Layout,以不同于系统内置的方式显示客制化的Toast 对象,如要在Toast 里显示图片(Drawable),方式如下:
Toast mToast01 = new Toast(this);
ImageView mView01 = new ImageView(this);
mView01.setImageResource(R.drawable.icon);
mToast01.setView(mView01);
mToast01.show();
或显示自定义的Layout Widget(如TextView),则写法如下:
Toast mToast01 = new Toast(this);
TextView mView01=new TextView(this);
mView01.setText("ToastWords");
mToast01.setView(mView01);
mToast01.show();
或者通过AlertDialog.Builder 来创建类似Toast 的信息对象,有兴趣的朋友可以实现看看,比较两者有何不同:
AlertDialog mADialog01 =new AlertDialog.Builder(this)
mADialog01.setTitle("Android 提示");
mADialog01.setMessage("this is a message");
mADialog01.show();