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();
    }
}
复制代码
posted @   成宇佳  阅读(28598)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示