显示图片的(自定义)吐司Toast

一般我们提示的时候都是直接提示文字的,其实Toast也可以显示图片

常用方法

  1. Toast.makeText(context,text,duration)这返回一个Toast对象
  2. toast.setDureation(duration)设置持续时间
  3. toast.setGravity(gravity,xOffest,yOffset)设置Toast的位置
  4. toast.setText(s);设置内容
  5. toast.show()显示内容
  6. toast.setView(View v)

例子

1.只显示图片的Toast

 public void showToast(){
      //获取一个Toast对象,为下面操作准备
      Toast toast = new Toast(this);
      ImageView img = new ImageView(this);
          //用系统提供的图片
      img.setImageResource(R.drawable.ic_launcher);
          //设置图片
      toast.setView(img);
      toast.show();        
 }
最后给一个按钮设定一个监听器,在onClick方法中调用对应的showToast方法就可以了。(下面两个例子同样省略这一步)

2.显示图片和文字

public void showToast2(){
      Toast toast = Toast.makeText(this, "这是一个有图片的吐司", Toast.LENGTH_LONG);
      ImageView img = new ImageView(this);
      img.setImageResource(R.drawable.ic_launcher);
          //得到toast的布局对象
      LinearLayout toast_layout = (LinearLayout) toast.getView();
      //为toast添加图片资源,第二个参数,0表示图片在上
      toast_layout.addView(img,1);
      toast.show();
 }

3.设计自己的Toast

有时候上面两种还没能满足自己的要求,就可以自定义布局(我在drawable中放了两张图片,詹姆斯和库里的)

准备布局文件

准备好你想要展示的Toast布局文件,我在layout文件夹新建了一个toast.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="horizontal">
 6     <ImageView
 7         android:layout_width="50dp"
 8         android:layout_height="90dp"
 9         android:background="@drawable/c2"
10         />
11     <TextView
12         android:layout_width="wrap_content"
13         android:layout_height="90dp"
14         android:gravity="center"
15         android:text="VS"
16         />
17     <ImageView        
18         android:layout_width="50dp"
19         android:layout_height="90dp"
20         android:background="@drawable/c1"
21         />     
22 </LinearLayout>

加载你的布局到Toast对象

public void showMyTosat(){
    //把一个布局变成一个View对象
    LayoutInflater inflater = LayoutInflater.from(this);
    View toast_layout = inflater.inflate(R.layout.toast, null);
    Toast toast = new Toast(this);
    //把获取到的View对象作为setView的参数
    toast.setView(toast_layout);
    toast.show();
}

 
原文地址:https://www.cnblogs.com/Mihai/p/5581130.html