AndroidStudio自定义Toast及其用法

目录

1.默认的Toast

2.居中的Toast

3.自定义的Toast


1.默认的Toast

Toast.makeText(getApplicationContext(),"默认的Toast",Toast.LENGTH_LONG).show();

格式为:Toast.makeText(所在的Activity的Context,"Toast显示的内容",Toast.LENGTH_LONG).show();

!!一定不要忘了.show哦,不然显示不出来~


2.居中的Toast

//maketext决定Toast显示内容
    Toast toastCenter = Toast.makeText(getApplicationContext(),"居中的Toast",Toast.LENGTH_LONG);

//setGravity决定Toast显示位置
    toastCenter.setGravity(Gravity.CENTER,0,0);
                    
//调用show使得toast得以显示
    toastCenter.show();


3.自定义的Toast

我自定义的Toast里面不要只有几个字,而是再加上一张图片,让Toast显得活泼一点。所以首先要写一个具有一张图片和一段文字的.xml文件,然后将其作为一个inflater塞进toast里面。

toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:orientation="vertical"
    android:gravity="center">

    !!图片
    <ImageView
        android:id="@+id/iv_toast"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginBottom="10dp"
        android:scaleType="fitCenter"/>
    !!文字
    <TextView
        android:id="@+id/tv_toast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="@color/colorPrimaryDark"
        />

</LinearLayout>

.java

Toast toast=new Toast(getApplicationContext()); 

//创建一个填充物,用于填充Toast
LayoutInflater inflater = LayoutInflater.from(ToastActivity.this);

//填充物来自的xml文件,在这个改成一个view
//实现xml到view的转变哦
View view =inflater.inflate(R.layout.toast,null);

//不一定需要,找到xml里面的组件,设置组件里面的具体内容
ImageView imageView1=view.findViewById(R.id.iv_toast);
TextView textView1=view.findViewById(R.id.tv_toast);
imageView1.setImageResource(R.drawable.smile);
textView1.setText("哈哈哈哈哈");

//把填充物放进toast
toast.setView(view);
toast.setDuration(Toast.LENGTH_SHORT);

//展示toast
toast.show();

猜你喜欢

转载自blog.csdn.net/qq_42183184/article/details/82533074