大智收藏Android知识首页投稿(暂停使用,暂停投稿)

Android菜鸟起飞|Toast的高级使用

2016-08-16  本文已影响442人  小胖0_0

Toast高级用法之设置带图片的Toast和自定义Toast

虽然google推出了更加美观实用的snackBar,但是Toast在某些开发场景中仍然是最合适的选择,所以学好Toast的用法还是很有必要的,何况这么简单:)

Toast的常用方法:

  1. Toast.makeText(context, text, duration); //返回值为Toast
  2. toast.setDuration(duration);//设置持续时间,毫秒为单位
  3. toast.setGravity(gravity, xOffset, yOffset);//设置toast位置,xOffset和yOffset分别为X轴和y轴的偏移量
  4. toast.setText(s);//设置提示内容
  5. toast.show();//显示toast

1. 设置带图片的Toast。用法十分简单,用代码说明:


Talk is cheap, Let`s code!


用法如下:

    //一个显示带图片的Toast方法
    public void ShowToast(){
        
        //创建一个toast
        Toast toast = Toast.makeText(this,"带图片的Toast",Toast.LENGTH_SHORT);

        //调用toast.getView()方法,强制转换一个LinearLayout作为view
        LinearLayout toast_layout = (LinearLayout)toast.getView();

        //定义一个ImageView
        ImageView imageView = new ImageView(this);

        //将图片传入imageView中
        imageView.setImageResource(R.mipmap.ic_launcher);

        //将imageView添加到view(toast_layout)中,在imageView后面加上参数即可改变文字和图片的相对位置,比如设置为addView(imageView,0)即可将文字放在图片的下面。
        toast_layout.addView(imageView);

        //显示toast
        toast.show();
    }

让后为其绑定点击事件即可,这里就不贴出来了。

Demo如下:

带图片的Toast

2. 设置自定义Toast。同样十分简单,还是用代码说明。


Talk is cheap, Let`s code!


用法如下:

首先需要定义一个toast_layout作为自定义toast的view,代码如下:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher" />
    <TextView
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="自定义toast" />
</LinearLayout>

在toast_layout中我们设置了一个imageView和一个textView分别用来显示图片和toast文字

然后编写自定义Toast方法,代码如下:

    //定义一个自定义显示toast的方法
    public void ShowToast2(){

        //使用LayoutInflater方法获取自定义的toast_layout作为toast的view
        LayoutInflater inflater = LayoutInflater.from(this);
        View toast_view = inflater.inflate(R.layout.toast_layout,null);

        //创建一个toast,这里需要出入context参数,传入this即可
        Toast toast = new Toast(this);

        //将toast_layout转换成的view传入toast.setView();方法中
        toast.setView(toast_view);

        //显示toast
        toast.show();
    }

Demo如下:

自定义Toast

完。

上一篇下一篇

猜你喜欢

热点阅读