带图片的Toast(st,toast,图片,移动开发)

时间:2024-05-02 16:13:59 作者 : 石家庄SEO 分类 : 移动开发
  • TAG :

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


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

带图片的Toast


用了两种方式实现:

一、自定义

1、新建一个xml布局 item_toast:

<?xmlversion="1.0"encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="wrap_content"android:layout_height="wrap_content"><RelativeLayoutandroid: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"><ImageViewandroid:id="@+id/img_hint"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerVertical="true"/><TextViewandroid: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"/></RelativeLayout></RelativeLayout>


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


2、在代码中实现。

//带图片的ToastpublicstaticvoidToastWithPicture(Activitycontext,Stringstr,intdrawable){if(toast!=null){toast.cancel();}Viewview=context.getLayoutInflater().inflate(R.layout.item_toast,null);TextViewtv_hint=(TextView)view.findViewById(R.id.tv_hint);ImageViewimg_hint=(ImageView)view.findViewById(R.id.img_hint);tv_hint.setText(str);img_hint.setImageResource(drawable);toast=newToast(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文件

//带图片的ToastpublicstaticvoidToastWithPicture(Activitycontext,Stringstr,intdrawable){if(toast!=null){toast.cancel();}ImageViewp_w_picpathView=newImageView(context);p_w_picpathView.setImageResource(drawable);toast=Toast.makeText(context,str,Toast.LENGTH_SHORT);toast.setGravity(Gravity.TOP,toast.getXOffset()/2,120);LinearLayoutview=(LinearLayout)toast.getView();view.setOrientation(LinearLayout.HORIZONTAL);view.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);//设置字体大小TextViewmsgText=(TextView)view.getChildAt(0);msgText.setTextSize(17);view.addView(p_w_picpathView,0);toast.show();}


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

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:带图片的Toast的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:Android音频开发(5):音频数据的编解码下一篇:

6 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18