一、什么是Toast?
吐司,显示一段文本(或者图片),然后再缓缓消失。
效果图如下:
二 、Toast怎么用?
不多说了,直接上代码吧,一看就懂。
demo分别测试了Toast显示文本、图片、图文
MainActivity的布局文件:
<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="com.Cactus.toastdemo.MainActivity" >
<Button
android:id="@+id/button1"
android:onClick="ViewTextClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="18dp"
android:text="Toast显示文本" />
<Button
android:id="@+id/button2"
android:onClick="ViewImageClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="19dp"
android:text="Toast显示图片" />
<Button
android:id="@+id/button3"
android:onClick="ViewallClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/button2"
android:layout_below="@+id/button2"
android:layout_marginRight="22dp"
android:layout_marginTop="26dp"
android:text="Toast显示图文" />
</RelativeLayout>
MainActivity:
package com.Cactus.toastdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ViewTextClick(View v)
{
//getApplicationContext() 应用程序上下文,全局,作用域为整个程序
//this 表示当前对象,当前界面的上下文
Toast.makeText(this,"哈哈哈哈哈",Toast.LENGTH_SHORT).show();
}
//显示图片
public void ViewImageClick(View v)
{
Toast t= new Toast(this);
ImageView imageView=new ImageView(this);
imageView.setImageResource(R.drawable.logo);
t.setView(imageView);
t.setDuration(Toast.LENGTH_SHORT);
//设置Toast位置
//参数(位置,偏移量,偏移量)
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
//显示图文
public void ViewallClick(View v)
{
Toast t=new Toast(this);
TextView tv=new TextView(this);
tv.setText("可爱的猫头鹰");
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.logo);
LinearLayout layout=new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setGravity(Gravity.CENTER);
layout.addView(imageView);
layout.addView(tv);
t.setView(layout);
t.setGravity(Gravity.CENTER, 0, 0);
t.setDuration(Toast.LENGTH_LONG);
t.show();
}
}