四种Toast的简单代码

第一种:默认Toast

Toast.makeText(this, "这是一个默认的吐司", 1).show();

四种Toast的简单代码_第1张图片
第二种:可以改变位置的Toast

Toast toast=Toast.makeText(this,"这是一个可以改变位置的tost",1);
toast.setGravity(Gravity.CENTER,50,50);//第二个参数如果/是大于0,向右偏移,小于0向左偏移;第三个参数大于0向下偏移,小于0向上偏移,以上偏移均在第一个参数你设置的位置的基础上
toast.show();

四种Toast的简单代码_第2张图片

第三种:添加图片的Toast

Toast toast2=Toast.makeText(this, "这是添加图片的吐司", 1);
LinearLayout view=(LinearLayout) toast2.getView();//获取当前toast所在的布局,.xml文件里的布局为线性布局

ImageView imageView=new ImageView(MainActivity.this);
            imageView.setImageResource(R.drawable.ic_launcher);//将图片加入toast所在的布局

view.addView(imageView,0);//没有第二个参数的时候默认图片在下面,如果,第二个参数为0,图片在上面,如果第二个参数为1,图片在下面
toast2.show();

四种Toast的简单代码_第3张图片
第四种:自定义布局的Toast

LayoutInflater inflater=LayoutInflater.from(this);
View root=inflater.inflate(R.layout.toast, null);//创建一个view
Toast toast3=new Toast(MainActivity.this);//完全自定的toast要用构造函数来生成对象
toast3.setView(root);//设置自定义toast样式

toast3.setDuration(Toast.LENGTH_LONG);//设置toast的显示时间
toast3.show();

自定义Toast布局文件


<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" 
    android:background="#fff5ee">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是一个自定义的toast" />

    <ImageView
        android:layout_marginTop="10dp"
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:layout_marginBottom="5dp"
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是一个机器人图片" />

LinearLayout>

四种Toast的简单代码_第4张图片

你可能感兴趣的:(Android,安卓中几种Toast)