当前位置: 移动技术网 > 移动技术>移动开发>Android > 基于自定义Toast全面解析

基于自定义Toast全面解析

2019年07月24日  | 移动技术网移动技术  | 我要评论
toast一般用来显示一行文字,用法比较固定: toast.maketext(context context,string message,int duratio

toast一般用来显示一行文字,用法比较固定:

toast.maketext(context context,string message,int duration);

但是有时候想用toast 来显示复杂的view甚至是带有图片的view时这时候就要用到自定义的toast,自定义toast主要用到一下几个方法如图:

1.setview()方法用来显示用户自定义的view.

2. setgravity()用来确定toast显示的位置.

3.setduration()用来设置toast显示的时间长短,只有两种选择,length_short,length_long,都是int型。

4.settext()用来显示一段文字,但是要注意的时settext()与setview(),不能同时使用不然就会出错。

下面通过一个完整的代码来看看如何实现一个自定义的toast:

toast_view.xml:

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  android:gravity="center"
>
  <imageview
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/tianjia_p"
    android:layout_gravity="center"
    />
  <textview
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="hello world"
    android:layout_gravity="center_horizontal"
    android:textsize="20dp"
    />
</linearlayout>

activity_main.xml:

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  >
  <button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/mybutton"
    android:text="button"
    />
</linearlayout>

toastutil:

public class toastutil {
  private static toast toast;
  public static void showtoast(int duration,view mview,context context)
  {
    if (toast==null) {
      toast = new toast(context);
    }
    toast.setduration(duration);
    toast.setview(mview);
    toast.show();
  }
}

mainactivity:

public class mainactivity extends appcompatactivity {
private view toast_view;
  private button button;
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    layoutinflater inflater=layoutinflater.from(this);
    toast_view =inflater.inflate(r.layout.toast_view,null);
    button=(button)findviewbyid(r.id.mybutton);
    button.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view v) {
        toastutil.showtoast(toast.length_short,toast_view,getapplicationcontext());
      }
    });
  }
}

上面的toastutil工具类 写的不好,大家可以自己改写自己的toastutil类。

以上这篇基于自定义toast全面解析就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网