zoukankan      html  css  js  c++  java
  • 显示图片的(自定义)吐司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();
    }

     
  • 相关阅读:
    浅析如何让 (a === 1 && a === 2 && a === 3) 返回 true
    浅析单点登录的三种实现方式
    浅析瀑布流布局原理及实现方式
    浅析Java中三目运算符可能产生的坑
    【转】IO
    [转]gomonkey学习
    从sha1的计算例子,理解计算机的数据表示?16进制输出?二进制输出??
    [转]Golang第三方包应该如何安装--在线和离线
    【转】goconvey使用
    go import 时 点号 和下划线的区别
  • 原文地址:https://www.cnblogs.com/Mihai/p/5581130.html
Copyright © 2011-2022 走看看