Android 更改 Toast 的默认位置方法
Android中Toast的默认位置在屏幕靠近底部的位置,这个默认位置有时候并不合适。比如页面上内容较少时,内容一般集中在屏幕上半部分,用户的注意力也集中在屏幕上半部分,默认位置的Toast用户可能没有注意到。还有可能是默认位置的Toast被用户的手挡住了。实践中感觉将Toast显示在屏幕的中部或中上部会比较好。如何修改Toast的默认位置呢?下面做一个简单的例子来演示一下。
先上截图:
布局文件activity_toast.xml代码如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onClickDefaultToast" android:text="点击显示默认位置的Toast" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onClickCenterToast" android:text="点击显示居中位置的Toast" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onClickTopToast" android:text="点击显示居中上部位置的Toast" /> </LinearLayout>
后台ToastActivity.java代码如下:
package chengyujia.demo.aty; import android.os.Bundle; import android.view.Display; import android.view.Gravity; import android.view.View; import android.widget.Toast; import chengyujia.demo.R; public class ToastActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_toast); } public void onClickDefaultToast(View v) { Toast.makeText(this, "默认位置的Toast", Toast.LENGTH_LONG).show(); } public void onClickCenterToast(View v) { Toast toast = Toast.makeText(this, "居中位置的Toast", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } public void onClickTopToast(View v) { Display display = getWindowManager().getDefaultDisplay(); // 获取屏幕高度 int height = display.getHeight(); Toast toast = Toast.makeText(this, "居中上部位置的Toast", Toast.LENGTH_LONG); // 这里给了一个1/4屏幕高度的y轴偏移量 toast.setGravity(Gravity.TOP, 0, height / 4); toast.show(); } }
以上这篇Android 更改 Toast 的默认位置方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Android中使用Expandablelistview实现微信通讯录界面
本文主要介绍了Android中使用Expandablelistview实现微信通讯录界面(完善防微信APP)的方法,具有一定的参考价值,下面跟着小编一起来看下吧2016-12-12Android开发实现Switch控件修改样式功能示例【附源码下载】
这篇文章主要介绍了Android开发实现Switch控件修改样式功能,涉及Android Switch开关控件样式设置与事件响应相关操作技巧,需要的朋友可以参考下2019-04-04Android基础入门之dataBinding的简单使用教程
DataBinding 是谷歌官方发布的一个框架,顾名思义即为数据绑定,下面这篇文章主要给大家介绍了关于Android基础入门之dataBinding的简单使用,文中通过实例代码介绍的非常详细,需要的朋友可以参考下2022-06-06Android 正则表达式验证手机号、姓名(包含少数民族)、身份证号
本篇文章主要介绍了Android 正则表达式验证手机号、姓名(包含少数民族)、身份证号的相关知识。具有很好的参考价值。下面跟着小编一起来看下吧2017-04-04
最新评论