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 }