默认的
Toast.makeText(getApplicationContext(),"默认的Toast",Toast.LENGTH_LONG).show();
居中的
//maketext决定Toast显示内容
Toast toastCenter = Toast.makeText(getApplicationContext(),"居中的Toast",Toast.LENGTH_LONG);
//setGravity决定Toast显示位置
toastCenter.setGravity(Gravity.CENTER,0,0);
//调用show使得toast得以显示
toastCenter.show();
自定义
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>
toast.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();
原文链接:https://blog.csdn.net/qq_42183184/article/details/82533074