Android 更改 Toast 的默認位置方法
Android中Toast的默認位置在屏幕靠近底部的位置,這個默認位置有時候并不合適。比如頁面上內(nèi)容較少時,內(nèi)容一般集中在屏幕上半部分,用戶的注意力也集中在屏幕上半部分,默認位置的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 的默認位置方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Android 再按一次返回鍵退出程序?qū)崿F(xiàn)思路
用戶退出應用前給出一個提示是很有必要的,因為可能是用戶并不真的想退出,而只是一不小心按下了返回鍵,大部分應用的做法是在應用退出去前給出一個Dialog提示框;個人覺得再按一次返回鍵退出程序很有必要,接下來介紹一些簡單實現(xiàn)2013-01-01
Android 6.0 無法在SD卡創(chuàng)建目錄的方法
今天小編就為大家分享一篇Android 6.0 無法在SD卡創(chuàng)建目錄的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
Android scheme 跳轉(zhuǎn)的設計與實現(xiàn)詳解
這篇文章主要介紹了Android scheme 跳轉(zhuǎn)的設計與實現(xiàn),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06
基于Vert.x和RxJava 2構(gòu)建通用的爬蟲框架的示例
這篇文章主要介紹了基于Vert.x和RxJava 2構(gòu)建通用的爬蟲框架的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
使用android隱藏api實現(xiàn)亮度調(diào)節(jié)的方法
使用android隱藏api實現(xiàn)亮度調(diào)節(jié)的方法,需要的朋友可以參考一下2013-05-05
Android 自定View實現(xiàn)仿QQ運動步數(shù)圓弧及動畫效果
這篇文章主要介紹了Android自定義view實現(xiàn)高仿QQ運動步數(shù)圓弧及動畫效果的實例代碼,本文涉及到繪制圓弧需要具備的知識點,需要的朋友可以參考下2016-10-10

