【例2-3】消息提示Toast示例
用三种方式展示Toast效果:默认方式、自定义方式和带图标方式。

教学视频
布局文件activity_toast.xml的源代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="消息提示Toast"
android:textSize="24sp" />
<Button
android:id="@+id/btn1"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="默认方式"
android:textSize="20sp" />
<Button
android:id="@+id/btn2"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="自定义方式"
android:textSize="20sp" />
<Button
android:id="@+id/btn3"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="带图标方式"
android:textSize="20sp" />
</LinearLayout>
控制文件ToastActivity.java源代码
package com.example.chap02;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
public class ToastActivity extends Activity implements OnClickListener
{
Button btn1,btn2,btn3;
Toast toast;
LinearLayout toastView;
ImageView imageCodeProject;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toast);
btn1=(Button)findViewById(R.id.btn1);
btn2=(Button)findViewById(R.id.btn2);
btn3=(Button)findViewById(R.id.btn3);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
}
public void onClick(View v)
{
if(v==btn1)
{
Toast.makeText(getApplicationContext(),
"默认Toast方式",
Toast.LENGTH_SHORT).show();
}
else if(v==btn2)
{
toast = Toast.makeText(getApplicationContext(),
"自定义Toast的位置",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0); //要求SDK版本低于30
toast.show();
}
else if(v==btn3)
{
toast = Toast.makeText(getApplicationContext(),
"带图标的Toast",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 80); //要求SDK版本低于30
toastView = (LinearLayout) toast.getView();
imageCodeProject = new ImageView(this);
imageCodeProject.setImageResource(R.drawable.icon);
toastView.addView(imageCodeProject, 0);
toast.show();
}
}
}
打开项目配置文件AndroidManifest.xml,配置要启动的Activity类名
<activity android:name=".ToastActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

