自定义Toast

  有时android原始的Toast不能满足我们的需要,我们可以自定义Toast,下面我们用例子来介绍自定义Toast。

  

  在toast_layout.xml文件中:

  

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3               android:id="@+id/toast_layout_root"
 4               android:orientation="horizontal"
 5               android:layout_width="fill_parent"
 6               android:layout_height="fill_parent"
 7               android:padding="8dp"
 8               android:background="#DAAA"
 9               >
10     <ImageView android:src="@drawable/droid"
11                android:layout_width="wrap_content"
12                android:layout_height="wrap_content"
13                android:layout_marginRight="8dp"
14                />
15     <TextView android:id="@+id/text"
16               android:layout_width="wrap_content"
17               android:layout_height="wrap_content"
18               android:textColor="#FFF"
19               />
20 </LinearLayout>

在.java文件中主要代码:

 1 LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
 2                 View view = inflater.inflate(R.layout.toast_layout, null);
 3                 TextView textView = (TextView) view.findViewById(R.id.text);
 4                 textView.setText(" a custom toast");
 5                 
 6                 Toast toast = new Toast(MainActivity.this);
 7                 toast.setGravity(Gravity.CENTER, 0, 0);
 8                 toast.setDuration(Toast.LENGTH_LONG);
 9                 toast.setView(view);  
10                 toast.show();

运行结果:

原文地址:https://www.cnblogs.com/SoulCode/p/5425244.html