Toasts (吐司)

Toasts

吐司通过弹出框对用户的操作进行简单反馈. 吐司只会占据屏幕的一小部分空间,并且当前的
Activity依然是可见和可交互的状态.

基本用法

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast.makeText(context,text,duration);
toast.show();

// 常用一下写法
Toast.makeText(context,text,duration).show();

Positioning your Toast

一个标准的toast显示在屏幕下方水平居中的位置. 我们可以通过使用setGravity(int,int,int)
方法设置显示位置.该方法接收三个参数.一个Gravity常量.一个x轴方向偏移量和一个y轴方向偏移量.

// 增加第二个参数可以实现右移.
// 增减第三个参数可以实现下移.
toast.setGravity(Gravity.TOP|Gravity.LEFT,0,0);

Creating a Custom Toast View .

可以创建一个布局文件,然后将布局文件对象作为toast.setView(View)方法的参数,这样就可以实现吧自定义布局的Toast.

自定义布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:id="@+id/toast_layout_root"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#DAAA"
              android:padding="8dp">
    <ImageView
        android:layout_width="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:layout_marginEnd="8dp"
        android:layout_height="wrap_content"/>
    <TextView
        android:layout_width="wrap_content"
        android:id="@+id/tv_txt"
        android:textColor="#FFF"
        android:layout_height="wrap_content"/>
</LinearLayout>

引用布局文件

    public void showCustomToast(){
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.toast_layout,(ViewGroup) findViewById(R.id.toast_layout_root));

        TextView txt = (TextView) layout.findViewById(R.id.tv_txt);
        CharSequence text = "Custom Toast View";
        txt.setText(text);

        Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.CENTER_VERTICAL ,0,0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(layout);
        toast.show();
    }

推荐阅读更多精彩内容