Android Toast 自定义

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:gravity="center"
 6     android:background="@android:color/holo_green_light"
 7     android:orientation="vertical" >
 8     
 9     <TextView
10         android:id="@+id/tv1"
11         android:layout_width="wrap_content"
12         android:layout_height="wrap_content"
13         android:text="text1"/>
14     
15      <TextView
16         android:id="@+id/tv2"
17         android:layout_width="wrap_content"
18         android:layout_height="wrap_content"
19         android:text="text2"/>
20 </LinearLayout>
item_toast
 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     android:layout_width="match_parent"
 3     android:layout_height="match_parent" 
 4     android:orientation="vertical">
 5 
 6     <Button
 7         android:layout_width="match_parent"
 8         android:layout_height="wrap_content"
 9         android:onClick="toast1"
10         android:gravity="center"
11         android:text="自定义Toast" />
12     <Button
13         android:layout_width="match_parent"
14         android:layout_height="wrap_content"
15         android:onClick="toast2"
16         android:gravity="center"
17         android:text="Toast.makeText" />
18 
19 </LinearLayout>
activity_main
 1 public class MainActivity extends Activity {
 2 
 3     @Override
 4     protected void onCreate(Bundle savedInstanceState) {
 5         super.onCreate(savedInstanceState);
 6         setContentView(R.layout.activity_main);
 7     }
 8     
 9     public void toast1(View v){
10         //Toast通过构造方法创建,但是必须手动设置视图(setView、setDuration)
11         Toast toast = new Toast(this);
12         
13         //动态加载布局
14         View view = getLayoutInflater().inflate(R.layout.item_toast, null);
15         TextView tv1 = (TextView) view.findViewById(R.id.tv1);
16         TextView tv2 = (TextView) view.findViewById(R.id.tv2);
17         
18         //view.setBackgroundResource(R.drawable.ic_launcher);
19         view.setBackgroundColor(Color.YELLOW);;
20         tv1.setText("提示");
21         tv2.setText("再按一次退出");
22         
23         toast.setView(view);
24         //Gravity.FILL_HORIZONTAL显示水平铺满,offset代表x,y轴上的偏移
25         toast.setGravity(Gravity.FILL_HORIZONTAL|Gravity.BOTTOM, 0, 500);
26         toast.setDuration(Toast.LENGTH_SHORT);
27         toast.show();
28         
29         
30     }
31 
32     public void toast2(View v){
33         Toast toast = Toast.makeText(this, "静态方法构建的Toast", Toast.LENGTH_SHORT);
34         toast.setGravity(Gravity.LEFT, 0, 800);
35         //只有静态方法构建的toast才能用setText()方法
36         toast.setText("你好吗?");//打印你好吗?
37         toast.setText(R.string.hello_world);//打印的是Hello world!
38         toast.show();
39     }
40     
41 }
MainActivity
原文地址:https://www.cnblogs.com/Claire6649/p/5968978.html