• 使用Toast进行用户提醒(转)


    Toast是Android提供的一个轻量级的用户提醒控件,使用也很简单,就相当一个极简的dialog!!!下面将向您介绍一些Toast的详细用法:

    1、普遍使用的方法:

      Context context = getApplicationContext();
        CharSequence text = "Hello toast!";
        int duration = Toast.LENGTH_SHORT;
    
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    一般情况下,我们都是这样使用Toast的,就跟其他的UI一样,初始化一个UI需要传入一个Context,这里是通过getApplicationContext获取应用程序的上下文!!!

    2、设置Toast显示的位置: 
    一般情况下,Toast显示在屏幕的下半屏幕中,就像下图所示的那样: 
    这里写图片描述
    我们可以通过代码更新Toast显示的位置:

     Context context = getApplicationContext();
        CharSequence text = "Hello toast!";
        int duration = Toast.LENGTH_SHORT;
    
        Toast toast = Toast.makeText(context, text, duration);
        toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
        toast.show();

    方法原型:

    public void setGravity(int gravity, int xOffset, int yOffset)

    这里的参数意义就不介绍,相信您根据名字就可以猜出来!!!

    改变位置后的Toast: 
    这里写图片描述

    3、自定义Toast的Layout: 
    Toast的布局如下所示:

     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                      android:id="@+id/custom_toast_container"
                      android:orientation="horizontal"
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:padding="8dp"
                      android:background="#DAAA"
                      >
            <ImageView android:src="@drawable/droid"
                       android:layout_width="wrap_content"
                       android:layout_height="wrap_content"
                       android:layout_marginRight="8dp"
                       />
            <TextView android:id="@+id/text"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:textColor="#FFF"
                      />
        </LinearLayout>

    在代码中解析layout,并将解析的布局添加至Toast中,具体代码如下所示:

      public void onShowCustomToast(View view) {
            LayoutInflater inflater = getLayoutInflater();
            View layout = inflater.inflate(R.layout.toast_layout,
                    null);
    
            TextView text = (TextView) layout.findViewById(R.id.text);
            text.setText("This is a custom toast");
    
            Toast toast = new Toast(getApplicationContext());
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.setDuration(Toast.LENGTH_LONG);
            toast.setView(layout);
            toast.show();
        }

    代码运行效果: 

    这里写图片描述

  • 相关阅读:
    dev c++ 中显示计算机中丢失libiconv2.dll
    poj 1456 Supermarket
    codeforce 867E Buy Low Sell High
    Java编写程序时出现警告:Resource leak: input is never closed 解决方法
    codeforce 8A
    CF1110B
    ZOJ 1914 Arctic Network
    POJ 1258 Agri-Net
    Poj 1751 Highways
    ZOJ 2158 Truck History
  • 原文地址:https://www.cnblogs.com/DreamRecorder/p/9256971.html
Copyright © 2020-2023  润新知