带图片的Toast-成都快上网建站

带图片的Toast

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

利通网站制作公司哪家好,找创新互联!从网页设计、网站建设、微信开发、APP开发、成都响应式网站建设等网站项目制作,到程序开发,运营维护。创新互联从2013年创立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联

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

带图片的Toast

用了两种方式实现:

一、自定义

1、新建一个xml布局 item_toast:




    

    

    

     
    

其中  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();
    }

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


网站栏目:带图片的Toast
文章URL:http://kswjz.com/article/gcpdhc.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流