如何正确使用Toast进行用户提醒
来源:互联网 发布:安装监控需要网络吗 编辑:程序博客网 时间:2024/06/13 12:21
本篇博客主要介绍如何使用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(); }
代码运行效果:
好了,关于Toast到这里差不多就结束了,有兴趣的朋友可以更加深入的研究学习,在这里就不赘述了!!!
这是我的微信公众号,如果可以的话,希望您可以帮忙关注一下,这将是对我最大的鼓励了,谢谢!!
代码稍后会上传至GitHub中:
代码地址:https://github.com/zhuyuqiang2017/Other
0 0
- 如何正确使用Toast进行用户提醒
- Toast提醒
- 如何提醒用户更新应用?
- Dialog、Toast、SnackBar给用户一个舒服的"提醒"
- 第4章--Toast提醒控件的使用
- 使用Toast(android中的一种提醒方式) & 建立监听 --4
- Android提醒技巧,Dialog、Toast和Snackbar的使用区别
- 如何正确使用width height 进行合理布局
- 如何使用Elastic Search正确的姿势进行搜索
- Elasticsearch:如何使用正确的姿势进行搜索
- 防止Toast重复提醒
- 如何正确进行异常处理
- Fragment里面如何使用Toast?
- 在Android中使用Toast进行提示
- 如何正确使用电烙铁
- 如何正确使用ads
- 如何正确使用异常
- 如何正确使用Timer
- 洛谷 1678 烦恼的高考志愿
- 白话threadlocal类
- 面向对象编程思想及入门知识
- 词云图
- 复习
- 如何正确使用Toast进行用户提醒
- Java并发(一)——Sychronized
- 闭包的应用
- 【算法题】非负整数的各位相加,直至变成个位数
- leetcode 71 similify path
- React系列之生命周期深入解析
- TSP_旅行商问题
- 《Java Web 程序设计与开发》读书笔记——JSP编程基础和JSP内置对象
- Python 3基础教程7-if语句