• Android 自定义Toast


    • Toast的基础用法

      Toast toast = Toast.makeText(getApplicationContext(), "Normarl toast", Toast.LENGTH_SHORT).show();
    • Toast显示的位置
      通常情况下Toast显示在整个界面的底部水平中间的位置,但是Toast现实的位置也是可以调整的,通过setGravity(int, int, int)
      方法来调整其位置

      Toast toast = Toast.makeText(getApplicationContext(), "Normarl toast", Toast.LENGTH_SHORT);
      toast.setGravity(Gravity.TOP | Gravity.RIGHT, 0, 0);
      toast.show();

      top_right.png
    • 自定义Toast
      创建自定义的layout文件,使用LayoutInflater渲染布局文件,最后使用ToastsetView(View)方法来实现

      如果不是自定义Toast,请使用makeText(Context, int, int)方法来创建Toast,不要使用Toast的构造方法

      自定义布局文件res/layout/custom_toast.xml

      <?xml version="1.0" encoding="utf-8"?>
      <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/ic_action_discover"
                   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"
                  android:text="This is a custom toast"/>
      </LinearLayout>

      Java 代码逻辑

      LayoutInflater inflater = getLayoutInflater();
                  View view = inflater.inflate(R.layout.custom_toast, null);
                  Toast toast = new Toast(getApplicationContext());
                  toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                  toast.setDuration(Toast.LENGTH_SHORT);
                  toast.setView(view);
                  toast.show();

    center.png
    • 点击一次显示一次Toast
      有时候连续点击会出现很多的Toast的提示,如果用户无操作,会导致toast提示一直存在,需要等很长时间
      才会消失,想要的效果是点击一次显示一次,
      private Toast mToast;
      private void showToast(String msg){
      if(mToast != null)
          mToast.cancel();
      mToast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);
      mToast.show();
      }
      根据自己的需求开发不同类型的Toast
  • 相关阅读:
    获取全部校园新闻
    爬取校园新闻首页的新闻的详情,使用正则表达式,函数抽离
    网络爬虫基础练习
    编写可维护的JavaScript
    markDown使用
    好文推荐系列---------JS模板引擎
    backbone框架思路
    如何获取URL中的参数
    如何使用NodeJs来监听文件变化
    sass基本用法(转载)
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/6627797.html
Copyright © 2020-2023  润新知