首页 > 代码库 > Toast

Toast

android Toast:

                                            (Toast实现的效果是在手机屏幕上显示一条消息,显示一段时间后信息会自动消失。)

        1.  默认效果

             用法:   Toast.makeText(getApplicationContext(), "默认Toast样式", Toast.LENGTH_SHORT).show();

                                        //该方法含有三个参数:1.  getApplicationContext(),2. "默认Toast样式", (表示要显示的内容)3. Toast.LENGTH_SHORT(显示的时间格式).

              

         2.自定义显示位置效果:

            用法:      toast = Toast.makeText(getApplicationContext(), "自定义位置Toast", Toast.LENGTH_LONG);

                                     //设置要显示的文字和,时间长短。
                          toast.setGravity(Gravity.CENTER, 0, 0);

                                        //setGravity:该方法用来设置显示位置(居中显示)
                          toast.show();

         3.带图片效果:

            用法:     

                       Toast toast = Toast.makeText(getApplicationContext(), "带图片的Toast", 3000);// 显示时间也可以是数字
                       toast.setGravity(Gravity.TOP, 0, 0);// 最上方显示
                       LinearLayout toastLayout = (LinearLayout) toast.getView();//总布局显示图片和文字。
                       ImageView imageView = new ImageView(getApplicationContext());
                       imageView.setImageResource(R.drawable.icon);    //imageView用来存放图片。
                       toastLayout.addView(imageView, 0);// 0 图片在文字的上方 , 1 图片在文字的下方
                       toast.show()

           4.完全自定义Toast:

              /**

                   LayoutInflater的使用,他的功能是将Layout中的XML文件转换成View,他是专门供Layout使用的Inflater,虽然Layout也是View子类,但在安卓中

                   如果想将,XML中的Layout 转换为View放入.java文件中操作,只能通过Inflater,而不能与findViewById()方法。

               */

                LayoutInflater inflater = getLayoutInflater();// LayoutInflater对象
                View layout = inflater.inflate(R.layout.custom_view, null);
                ImageView imageView = (ImageView) layout.findViewById(R.id.imageView);
                TextView text = (TextView) layout.findViewById(R.id.textView);
                imageView.setImageResource(R.drawable.icon);
                text.setText("完全自定义的Toast");
                Toast toast = new Toast(getApplicationContext());
                // 底部 、水平居中,X偏移50 Y偏移50
                toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 50, 50);
                toast.setDuration(Toast.LENGTH_SHORT);
                toast.setView(layout);
                toast.show();                                                                                                                             2016-11-23   22:05:28

 

Toast