zoukankan      html  css  js  c++  java
  • Android开发必知--自定义Toast提示

      开发过Android的童鞋都会遇到一个问题,就是在打印Toast提示时,如果短时间内触发多个提示,就会造成Toast不停的重复出现,直到被触发的Toast全部显示完为止。这虽然不是什么大毛病,但在用户体验上听让人发狂的。本篇博文就是介绍怎么自定义Toast提示,不仅能完美的解决上述问题,而且还能自定义提示UI。

      先看一下效果图(左边是普通的toast提示,右边是自定义的):

             

     光看效果图,可能还感受不到什么不同,点击多次之后就会发现文章开头说的情况。

    接着看一下自定Toast的开发步骤:

    ·第一步:准备自定义Toast的布局文件。

     1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     2     xmlns:tools="http://schemas.android.com/tools"
     3     android:id="@+id/container"
     4     android:layout_width="match_parent"
     5     android:layout_height="match_parent" 
     6     android:orientation="vertical" >
     7 
     8     <TextView
     9         android:id="@+id/txt_toast"
    10         android:layout_width="wrap_content"
    11         android:layout_height="wrap_content"
    12         android:padding="5dp"
    13         android:background="#ccc"
    14         android:textColor="#fff" />
    15     
    16 </LinearLayout>

    ·第二步:编写一个独立的自定义Toast类或者方法,方便调用。

     1 public void myToast(String msg){
     2         if(toast == null){
     3             toast = new Toast(this);
     4         }
     5         toast.setDuration(0);
     6         toast.setGravity(Gravity.CENTER, 0, 0);
     7         LayoutInflater inflater = this.getLayoutInflater();
     8         LinearLayout toastLayout = (LinearLayout)inflater.inflate(R.layout.toast, null);
     9         TextView txtToast = (TextView)toastLayout.findViewById(R.id.txt_toast);
    10         txtToast.setText(msg);
    11         toast.setView(toastLayout);
    12         toast.show();
    13     }

    ·第三步:调用普通Toast提示,和自定义Toast,查看效果。布局文件只有两个按钮,比较简单就不贴了。

     1 bnToast.setOnClickListener(new OnClickListener() {
     2         @Override
     3         public void onClick(View arg0) {
     4             Toast.makeText(getApplicationContext(), "普通toast提示", Toast.LENGTH_SHORT).show();
     5         }
     6 });
     7 bnMyToast.setOnClickListener(new OnClickListener() {
     8         @Override
     9         public void onClick(View arg0) {
    10             myToast("自定义toast提示");
    11         }
    12});
  • 相关阅读:
    Linux下 高性能、易用、免费的ASP.NET服务器
    K-means算法
    K-means算法
    机器学习之深度学习
    机器学习之深度学习
    Tracking-Learning-Detection (TLD算法总结)
    Tracking-Learning-Detection (TLD算法总结)
    机器学习技法之Aggregation方法总结:Blending、Learning(Bagging、AdaBoost、Decision Tree)及其aggregation of aggregation
    机器学习技法之Aggregation方法总结:Blending、Learning(Bagging、AdaBoost、Decision Tree)及其aggregation of aggregation
    迭代是人,递归是神(迭代与递归的总结:比较)
  • 原文地址:https://www.cnblogs.com/codingblock/p/4705694.html
Copyright © 2011-2022 走看看