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

    <?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();
    }
    复制代码

  • 相关阅读:
    使用 Spring + CXF 发布 REST 服务
    在web项目中使用CXF暴露REST服务
    学习SpringMVC——从HelloWorld开始
    java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
    安装maven时JAVA_HOME的配置小问题
    java 接口的实现和继承关系
    servlet的两种配置方式
    C# MainWindowHandle为0的解决方法
    C# WindowsMediaPlayer 的一些用法
    C# 获取MP3信息
  • 原文地址:https://www.cnblogs.com/youshashuosha/p/5587414.html
Copyright © 2011-2022 走看看