Toast

一、Toast的简介

Toast是Android中用来显示显示信息的一种机制,和Dialog不一样的是,Toast是没有焦点的,而且Toast显示的时间有限,过一定的时间就会自动消失。

二、简单的Toast

Toast toast = Toast.makeText(getApplicationContext(), "我是一个Toast", Toast.LENGTH_SHORT);
               Spanned spanned= Html.fromHtml("我是<img src=''/>一个<font color='#ff0000'>Toast</font>", new Html.ImageGetter() {
                   @Override
                   public Drawable getDrawable(String source) {
                       Drawable drawable=getResources().getDrawable(R.mipmap.ic_launcher);
                       drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());

                       return drawable;
                   }
               },null);
                toast.setText(spanned);
                toast.setGravity(Gravity.LEFT, 0, 0);
                toast.show();

运行结果如下
这里写图片描述

三、自定义Toast

自定义Toast与简单Toast的区别就是弹出信息的布局是自己进行设置的,通过在layout中新建一个新的xml文件toast_item进行内容的布局。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/textview_toast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ff0000"/>
    <ImageView
        android:id="@+id/image_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"/>
    <TextView
        android:id="@+id/textview_toast2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="内容"/>

</LinearLayout>

2.要在MainActivity中新建一个适配器,将内容适配到自定义的item中

    Toast toast2=new Toast(getApplicationContext());
                LayoutInflater inflater=getLayoutInflater();
                View toastView=inflater.inflate(R.layout.toast_item, null);
                TextView textView_title= (TextView) toastView.findViewById(R.id.textview_toast);
                textView_title.setText("我是一个自定义Toast");
                toast2.setView(toastView);
                toast2.setDuration(Toast.LENGTH_SHORT);
                toast2.show();

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值