欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

Android 更改 Toast 的默认位置方法

时间:2021-04-23 09:26:53|栏目:Android代码|点击:

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实现气泡布局/弹窗效果 气泡尖角方向及偏移量可控

栏    目:Android代码

下一篇:Android PopupWindow实现左侧弹窗效果

本文标题:Android 更改 Toast 的默认位置方法

本文地址:http://www.codeinn.net/misctech/106805.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有