自定义带图片的Toast

布局很简单就是一个ImageView和TextView横向排列

1、toast.xml

 

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
              android:layout_width="80dp"  
              android:layout_height="30dp"  
              android:padding="10dp"  
              android:gravity="center"  
              android:background="@drawable/toaststyle"  
              android:orientation="horizontal">  
  
    <ImageView  
        android:layout_width="30dp"  
        android:layout_height="30dp"  
        android:id="@+id/imageView"/>  
  
    <TextView  
        android:id="@+id/message"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_weight="1"  
        android:shadowColor="#bbfcd603"  
        android:shadowRadius="2.75"  
        android:textColor="#ffffff"  
        />  
</LinearLayout>  

2、toaststyle.xml

 

 

<?xml version="1.0" encoding="utf-8"?>  
<shape xmlns:android="http://schemas.android.com/apk/res/android">  
    <solid android:color="#21211d" />  
    <corners android:topLeftRadius="10dp"  
             android:topRightRadius="10dp"  
             android:bottomRightRadius="10dp"  
             android:bottomLeftRadius="10dp"/>  
</shape>

3、CustomToast.java  自定义的Toast方法

 

 

public class CustomToast {  
    private static TextView mTextView;  
    private static ImageView mImageView;  
  
    public static void showToast(Context context, String message) {  
        //加载Toast布局  
        View toastRoot = LayoutInflater.from(context).inflate(R.layout.toast, null);  
        //初始化布局控件  
        mTextView = (TextView) toastRoot.findViewById(R.id.message);  
        mImageView = (ImageView) toastRoot.findViewById(R.id.imageView);  
        //为控件设置属性  
        mTextView.setText(message);  
        mImageView.setImageResource(R.mipmap.ic_launcher);  
        //Toast的初始化  
        Toast toastStart = new Toast(context);  
        //获取屏幕高度  
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);  
        int height = wm.getDefaultDisplay().getHeight();  
        //Toast的Y坐标是屏幕高度的1/3,不会出现不适配的问题  
        toastStart.setGravity(Gravity.TOP, 0, height / 3);  
        toastStart.setDuration(Toast.LENGTH_LONG);  
        toastStart.setView(toastRoot);  
        toastStart.show();  
    }  
}  


代码很详细,不用多解释,这里只是一个简单的例子,大家感兴趣的可以自己添加喜欢的设计,顺便说一下,这里很多属性都可以自己抽出来的当成变量的,大家可以根据自己的风格封装乘工具类使用。当然也可以自定义图片,设置图片,这样更灵活,这里只是写个demo就没写进来了

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值