Android Toast 的几种简单设置

     最近在改客户的的需求,是关于 toast 的,网上学习了下, 下面列出几种简单的设置, 以供有需要的朋友们参考,不足之处请各位指正,谢谢.

1.最简单的 Toast

Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();

Toast.LENGTH_SHORT/Toast.LENGTH_LONG 是android 自定义的显示时长,toast show的时间都比较短.

2.带有 Layout 的Toast, 包含有 ImageView 和 TextView.

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_custom_styles,(ViewGroup) findViewById(R.id.ll_Toast));
ImageView image = (ImageView) layout.findViewById(R.id.iv_ImageToast);
image.setImageResource(R.drawable.ic_launcher);
TextView text = (TextView) layout.findViewById(R.id.tv_TextToast);
text.setText("自定义Toast的样式");
Toast toast = new Toast(this);                                                                                                                                                   toast.setGravity(Gravity.LEFT | Gravity.TOP, 20, 50);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

Layout  toast_custom_styles 如下:

<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/ll_Toast"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:background="#ffffffff"
      android:orientation="vertical" >
 
      <LinearLayout
         android:id="@+id/ll_ToastContent"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginBottom="1dp"
         android:layout_marginLeft="1dp"
         android:layout_marginRight="1dp"
         android:background="#44000000"
         android:orientation="vertical"
         android:padding="15dip" >
 
         <ImageView
             android:id="@+id/iv_ImageToast"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="center" />

         <TextView
             android:id="@+id/tv_TextToast"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:gravity="center"
             android:paddingLeft="10dp"
             android:paddingRight="10dp"
             android:textColor="#ff000000" />
     </LinearLayout>
 
 </LinearLayout>

3.设置 Toast 的显示时长

private void CustomTimeToast() {
         final Toast toast = Toast.makeText(this, "自定义Toast的时间",Toast.LENGTH_LONG);
         final Timer timer = new Timer();
         timer.schedule(new TimerTask() {
             @Override
             public void run() {
                 toast.show();
             }
         }, 0, 3000);// 3000表示点击按钮之后,Toast延迟3000ms后显示
         new Timer().schedule(new TimerTask() {
             @Override
             public void run() {
                 toast.cancel();
                 timer.cancel();
             }
         }, 5000);// 5000表示Toast显示时间为5秒
 
     }

正是这个解决了我的问题.网上延长toast 显示的方法好几种, 这种是最简单的

猜你喜欢

转载自blog.csdn.net/bingsfsg/article/details/86251878