android toast 带图片,带图片的Toast

自定义Toast实践:带图片与文字居中对齐的实现

项目快结束了,终于有空可以总结下在开发中遇到的一些问题。

需要在文字的左侧显示图片 效果图如下:

9dc02c4cb9f9d7a9783bdc4afb70ed24.png

用了两种方式实现:

一、自定义

1、新建一个xml布局 item_toast:<?xml  version="1.0" encoding="utf-8"?>

android:layout_width="wrap_content"

android:layout_height="wrap_content" >

android:layout_width="wrap_content"

android:layout_height="50dp"

android:orientation="horizontal"

android:paddingRight="10dp"

android:paddingLeft="10dp"

android:background="@drawable/toast_bg"

android:gravity="center" >

android:id="@+id/img_hint"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerVertical="true"/>

android:id="@+id/tv_hint"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerVertical="true"

android:layout_toRightOf="@+id/img_hint"

android:layout_marginLeft="5dp"

android:text="TextView"

android:textSize="17sp"

android:textColor="@color/white" />

其中  android:background="@drawable/toast_bg" 为Toast带圆角的背景

2、在代码中实现。//带图片的Toast

public static void ToastWithPicture(Activity context, String str,int drawable) {

if(toast != null){

toast.cancel();

}

View view = context.getLayoutInflater().inflate(R.layout.item_toast, null);

TextView tv_hint = (TextView) view.findViewById(R.id.tv_hint);

ImageView img_hint = (ImageView) view.findViewById(R.id.img_hint);

tv_hint.setText(str);

img_hint.setImageResource(drawable);

toast = new Toast(context);

toast.setGravity(Gravity.TOP, toast.getXOffset() / 2, 120);

toast.setDuration(0);

toast.setView(view);

toast.show();

}

由于项目中需要用到Toast的地方非常多,所以我把它封装成一个方法,放在Utility类中。需要时直接调用就可以啦。Utility.ToastWithPicture(this, getResources()

.getString(R.string.hint_talk_unlock),R.drawable.img_unlock);

二、不需要新建xml文件//带图片的Toast

public static void ToastWithPicture(Activity context, String str,int drawable) {

if(toast != null){

toast.cancel();

}

ImageView p_w_picpathView = new ImageView(context);

p_w_picpathView.setImageResource(drawable);

toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);

toast.setGravity(Gravity.TOP, toast.getXOffset() / 2, 120);

LinearLayout view = (LinearLayout) toast.getView();

view.setOrientation(LinearLayout.HORIZONTAL);

view.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);

//设置字体大小

TextView msgText = (TextView) view.getChildAt(0);

msgText.setTextSize(17);

view.addView(p_w_picpathView, 0);

toast.show();

}

但是这种方法好像没办法让文字和图片居中对齐。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值