显示图片的(自定义)吐司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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <ImageView android:layout_width="50dp" android:layout_height="90dp" android:background="@drawable/c2" /> <TextView android:layout_width="wrap_content" android:layout_height="90dp" android:gravity="center" android:text="VS" /> <ImageView android:layout_width="50dp" android:layout_height="90dp" android:background="@drawable/c1" /> </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); toast.setView(toast_layout); toast.show(); }
复制代码

 


转载于:https://www.cnblogs.com/youshashuosha/p/5587414.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值