当前位置: 移动技术网 > IT编程>移动开发>Android > Android 更改 Toast 的默认位置方法

Android 更改 Toast 的默认位置方法

2019年07月24日  | 移动技术网IT编程  | 我要评论

太阳城包杀网,嫡妻不好惹 19楼,解脱美眉内衣

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 的默认位置方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网